--00163646d8f27e847b0462cfad07
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: 7bit

On Fri, Feb 13, 2009 at 11:07 AM, David A. Black <dblack / rubypal.com> wrote:

> On Sat, 14 Feb 2009, James Coglan wrote:
> Regardless of whether they're *supposed* to, the Rubies I've used before
>
>> 1.8.7 actually do iterate in insertion order. Could be machine/OS
>> specific,
>> a fluke, whatever. The point is that 1.8.7 definitely does not iterate in
>> the order that keys appear in a literal, at least on my machine. If this
>> is
>> supposed to now be defined behaviour I'll investigate further and file a
>> bug
>> if necessary.
>>
>
> I think it probably is machine-dependent, or something like that. I've
> never heard of hash order being anything but "not guaranteed" before
> 1.9 -- except that if you iterate twice, I believe it definitely
> happens in the same order both times (though I'm not 100% sure that
> that's actually specified or guaranteed either).
>

No, it's in the absence of key collisions, it's really determined by the
hash values of the keys,  The iteration is over the hash buckets and hash
buckets marked as empty are skipped.

Consider your examples which I've excerpted:

% all-ruby -e 'h  2b", 1a"}; p h'
...
ruby-1.8.6head(2009-02-13p330) {1a", 2b"}
...
ruby-1.8.7head(2009-02-13p116) {1a", 2b"}
...
ruby-1.9.1p0(2009-01-30r21907) {2b", 1a"}

Note that for Ruby 1.8.6 and 1.8.7, the iteration order is by the sort order
of the keys.  But that's just a side-effect of the hash of a fixnum being
just the internal immediate representation which happens to be n*2 + 1 for a
Fixnum n:

irb(main):001:0> 1.hash
3
irb(main):002:0> 2.hash
5

Had you used what is arguably the more natural order in the literal, i.e. {1
"a", 2 "b"} it would appear as if iteration was by insertion order,
but that's just an accidental artifact.

I suspect that those who observed that Ruby 1.8.7 'preserves' insertion
order are looking at specific artificial cases like this.
-- 
Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Twitter: http://twitter.com/RickDeNatale

--00163646d8f27e847b0462cfad07--