Is the order of the values returned by Ruby’s Hash::each_value{ |val| block } somehow defined? I.e. for a given hash is the order of values in the iterations of the loop always* the same?
I wonder if it is so, as the key-value pairs of hashes are not sorted unlike the values of an array.
Given the following example:
myhash = { :a => 100, :b => 200, :z => 9, :e => 101 }
myhash.each_value { |val|
puts val
}
Does Ruby ensure it always* prints
100
200
9
101
Bonus question in case it is defined:
What are the prerequisites that the order is defined? Does it only apply for hard-coded hashes as the example?
[*]: “always” should be read as ‘on each execution and on any system with a working Ruby 1.9+‘.
In Ruby 1.8, Hashes are not ordered and the values will be returned in an arbitrary order that you cannot depend upon. In Ruby 1.9, Hashes are ordered based on the time the keys were inserted (first insertion positioned first, etc…).
You specified in a footnote that “‘always’ should be read as ‘on each execution and on any system with a working Ruby 1.9+’.”. By that definition of “always”, the answer is “yes” 😉
From the Ruby 1.8.7 Hash docs:
From the Ruby 1.9.3 Hash docs: