Is every iterator in ruby ​​guaranteed the same order on the same elements every time?

I am doing something like this with a list of 'a':

a.each_with_index |outer, i| a.each_with_index |inner, j| if(j > i) # do some operation with outer and inner end end end 

If the iterator does not use the same order, this will not work. I don’t care what order is in fact, I just need two .each_with_index iterators to use the same order.

I would suggest that this would be a property of an array that has a fixed order, and I'm just paranoid so the iterator doesn't use that order ...

+7
source share
4 answers

It depends on the specific Enumerable you are working on.

Arrays, for example, will always return elements in the same order. But other enumerated objects are not guaranteed to behave this way. A good example of this is the 1.8.7 base hash. This is why many frameworks (primarily ActiveSupport) implement OrderedHash.

One interesting note: even Hash will return objects in the same order if the hash has not changed between calls to each . Although many objects behave this way, relying on this subtlety is probably not a good idea.

So no. The common each does not always return objects in the same order.

PS Now Ruby 1.9 hashes are now streamlined http://www.igvita.com/2009/02/04/ruby-19-internals-ordered-hash

+15
source

I have not looked at your actual code, but here is your answer taken from the Ruby API docs :

Arrays are ordered, whole indexed collections of any object.

So, yes, you are paranoid, but it is true that it is good when you develop?

+6
source

An array is, by definition, an ordered list of elements. Therefore, you should not have a problem with this.

+2
source

It depends on the particular enumerable. Of course, the array will always be repeated in the obvious order.

It would be really crazy for someone to implement the each method, which will go through the same collection differently, but the only actual limitation for such a “function” will be in the documentation for the class that mixes in enumerations. Well, that’s the sanity of the developers.

I can almost imagine some kind of cryptographic API that deliberately crossed the collection in an unpredictable way.

+1
source

All Articles