From: dblack@... Date: 2006-07-25T22:53:10+09:00 Subject: Re: Hash order bug? Hi -- On Tue, 25 Jul 2006, Javier Valencia wrote: > dblack@wobblini.net wrote: > >> Hi -- >> >> On Tue, 25 Jul 2006, Javier Valencia wrote: >> >>> I have this piece of simple code: >>> >>> ---------------------------------------------- >>> def foo >>> return 5 >>> end >>> >>> a = {:gr => false, :und => false, :det => true, :sta => false, :inv => >>> false} >>> puts a.inspect >>> ---------------------------------------------- >>> >>> when I execute it i get a totally unordered hash: >>> >>> ---------------------------------------------- >>> ruby pro.rb >>> {:inv=>false, :gr=>false, :und=>false, :det=>true, :sta=>false} >>> ---------------------------------------------- >>> >>> Now, i delete the foo function from the code (the foo function don't do >>> nothing at all), and i get a well ordered hash: >>> >>> ---------------------------------------------- >>> ruby pro.rb >>> {:gr=>false, :und=>false, :det=>true, :sta=>false, :inv=>false} >>> ---------------------------------------------- >>> >>> >>> What's happening? all my code is behaving wrong because of that. >> >> >> Hashes are unordered. If you need an ordered collection, you'll need >> to use an array. >> >> >> David >> > > Oh my god, i didn't know it, sorry. Is that a missing feature? Debate rages on this point :-) It's mostly a speed issue, I think. At least my memory is that Matz's latest statement was to the effect that he would do it if it could be done efficiently. The question came up during a lunch here at OSCON (with me, Jim Weirich, Pat Eyler, and a fellow named Nicolas whose last name I'm afraid I don't remember) as to whether making hashes ordered in a future Ruby would break any existing code. I think the answer is no, which is kind of interesting considering what a major change it would be. It's a case where the feature would be purely additive. David -- http://www.rubypowerandlight.com => Ruby/Rails training & consultancy http://www.manning.com/black => RUBY FOR RAILS (reviewed on Slashdot, 7/12/2006!) http://dablog.rubypal.com => D[avid ]A[. ]B[lack's][ Web]log dblack@wobblini.net => me