REE 1.8.7-2011.03, Is `Enumerator#each` guaranteed to return elements in the same order as `Enumerable#to_a`

StackOverflow https://stackoverflow.com/questions/13828660

문제

I'm running into an issue where records from an ActiveRecord association are being returned in an order that I didn't expect. This is easy enough to fix going forward, but some code that is already in production assumes a certain order, and that order is significant in my case - in fact it's critical.

I've narrowed down the way to fix the old stuff to this basic problem: if "Enumerable#each" is guaranteed to return a consistent order of ActiveRecord records on an association, then at least I know I'm dealing with a consistently broken assumption, which is fixable. If it is NOT guaranteed then I might be hosed.

So my question is, in Ruby Enterprise Edition, Release 2011.03, does the Enumerable#each method return the elements in the Enumerable in the same order as if I would call Enumerable#to_a (a function defined on Object

I've downloaded the REE code from github, and checked out the tag for this release (and I've verified that I'm using the same Ruby versions in my development, staging, and production environments). The trouble is I'm not great with reading C, and so I can only say that I'm pretty confident that the order is the same, but my C reading skills aren't so great.

도움이 되었습니까?

해결책

Yes, it's guaranteed; #to_a effectively just collects the results of #each and returns them in a new array.

enum_to_a creates a new array, then calls collect_all as a block parameter to its own each. collect_all simply performs rb_ary_push(ary, i);, which pushes the given value onto the created array. In Ruby, this would be:

array = []
enum.each {|v| array.push v }

Hope that helps!

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top