nobilik
nobilik

Reputation: 736

Unexpectable result of `zip` usage

I have two arrays. First is array of objects from DB @groups = Group.where(blabla). Second comes from API request response = [false, false, something]. When I try to go through both of them:

@groups.zip(response).each do |group, r|
.
.
end

@groups array starts from second element and puts first in the last iteration. Why it happens? With yi = @groups.pluck(:id) I can see that the order of the array is proper!

To be more clear I expect result = [[403, false], [404, false], [405, something]] , but I have result = [[404, false], [405, false], [403, something]]

Upvotes: 0

Views: 28

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

AFAIU, the problem has nothing to do with ruby, it is DB engine issue. Group.where(blabla) is basically executed as SELECT * FROM groups WHERE blabla. Unless one have explicitly specified the order of this query, the result set order is not guaranteed.

pluck is translated to slightly different query, and DB engine might return the result set in the different order.

Use explicit ordering in your queries to retrieve the results in the specific order.

Upvotes: 1

Related Questions