Ruby, since v1.9, supports a deterministic order when looping through a hash; entries added first will be returned first.
Does this apply to literals, i.e. will { a: 1, b: 2 }
always yield a before b?
I did a quick experiment with Ruby 2.1 (MRI) and it was in fact consistent, but to what extent is this guaranteed by the language to work on all Ruby implementations?
There are couple of locations where this could be specified, i.e. a couple of things that are considered "The Ruby Language Specification":
The ISO spec doesn't say anything about
Hash
ordering: it was written in such a way that all existing Ruby implementations are automatically compliant with it, without having to change, i.e. it was written to be descriptive of current Ruby implementations, not prescriptive. At the time the spec was written, those implementations included MRI, YARV, Rubinius, JRuby, IronRuby, MagLev, MacRuby, XRuby, Ruby.NET, Cardinal, tinyrb, RubyGoLightly, SmallRuby, BlueRuby, and others. Of particular interest are MRI (which only implements 1.8) and YARV (which only implements 1.9 (at the time)), which means that the spec can only specify behavior which is common to 1.8 and 1.9, whichHash
ordering is not.The RubySpec project was abandoned by its developers out of frustration that the ruby-core developers and YARV developers never recognized it. It does, however, (implicitly) specify that
Hash
literals are ordered left-to-right:That's the spec for
Hash#keys
, however, the other specs test thatHash#values
has the same order asHash#keys
,Hash#each_value
andHash#each_key
has the same order as those, andHash#each_pair
andHash#each
have the same order as well.I couldn't find anything in the YARV testsuite that specifies that ordering is preserved. In fact, I couldn't find anything at all about ordering in that testsuite, quite the opposite: the tests go to great length to avoid depending on ordering!
The Flanagan/matz book kinda-sorta implicitly specifies
Hash
literal ordering in section 9.5.3.6Hash
iterators. First, it uses much the same formulation as the docs:But then it goes on:
And in those examples, it actually uses a literal:
In his comment, @mu is too short mentioned that
and in another comment that
Unfortunately, that is not true:
So, depending on how you interpret that line from the book and depending on how "specification-ish" you judge that book, yes, ordering of literals is guaranteed.
From the documentation: