2009/2/13 William James <w_a_x_man / yahoo.com>

> Stefan Lang wrote:
>
> > Iteration order is undefined, even for hash literals.
> > This is on my machine:
> >
> >     $ ruby -v -e '{2 => 0, 1 => 0}.each_pair { |k,v| p k }'
> >     ruby 1.8.6 (2007-09-24 patchlevel 111) [x86_64-linux]
> >     1
> >     2
> >
> > Your code happened to work by chance.
> >
> > > To work with 1.8.7, you need to create an empty hash
> > > and add keys one by one rather than putting them all in a hash
> > > literal (see the patch).
> >
> > Do I understand that the code relies on insertion order now?
> > Then it's still working by chance in case it works at all.
> >
> > Stefan
>
> +1
>
> Mr. Coglan seems not to understand how a hash-table is implemented.
> One cannot predict the iteration order because he cannot know in which
> bucket each element has been stored.  Furthermore, it makes no sense
> at all to be concerned about iteration-order for a hash-table.
>
> If one is concerned about iteration-order, he should use an
> association-list.



I do know how hash tables work, I was responding to the question of whether
any code was broken by 1.8.7. I've conceded elsewhere in this thread that no
iteration order was ever guaranteed for 1.8, and that the question of
whether this counts as a true backward incompatibility is a grey area at
best.

I am using an ordered hash implementation, but was initialising it using
hash literals, which obviously does not work if iteration order is different
from source order. I've since fixed the bug by adding keys explicitly one by
one.

This begs the question of whether 1.9 should guarantee insertion order for
hashes. Since hashes are not inherently ordered beings, wouldn't it make
more sense to provide an OrderedHash subclass that explicitly provides that
behaviour? At least then it would be clearer if you were using a 1.9 feature
that won't work on 1.8.