From: "David A. Black" Date: 2009-02-14T02:14:18+09:00 Subject: Re: If you are unhappy with the direction of Ruby 1.8.7+, respond Hi -- On Sat, 14 Feb 2009, Rick DeNatale wrote: > On Fri, Feb 13, 2009 at 11:07 AM, David A. Black 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 = {2=>"b", 1=>"a"}; p h' > ... > ruby-1.8.6head(2009-02-13p330) {1=>"a", 2=>"b"} > ... > ruby-1.8.7head(2009-02-13p116) {1=>"a", 2=>"b"} > ... > ruby-1.9.1p0(2009-01-30r21907) {2=>"b", 1=>"a"} > > 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. That's why I didn't :-) David -- David A. Black / Ruby Power and Light, LLC Ruby/Rails consulting & training: http://www.rubypal.com Coming in 2009: The Well-Grounded Rubyist (http://manning.com/black2) http://www.wishsight.com => Independent, social wishlist management!