Sunday, October 11, 2009

Ruby: 1.8.x hashes are not sorted


What?
I know, it stinks. But Ruby 1.9.x has sorted Hashes (in insertion oreder)

# Ruby 1.8.7irb(main):001:0> {:a=>"a", :c=>"c", :b=>"b"}=> {:a=>"a", :b=>"b", :c=>"c"}# Ruby 1.9.1 (in insertion order)irb(main):001:0> {:a=>"a", :c=>"c", :b=>"b"}=> {:a=>"a", :c=>"c", :b=>"b"}

More info here: http://www.igvita.com/2009/02/04/ruby-19-internals-ordered-hash/

Wait. I can't migrate over to Ruby 1.9.x. So what?
There are a lot of reasons why you wouldn't migrate, one of which being that after 2 years, Komodo IDE is still unable to debug 1.9 code.
Anyway. There's a trick to have sorted hashes in Ruby 1.8. Just maintain a sorted array of keys, and then each time you want to traverse your hash, do so via the parallel array.
See an example of this technique in my YADL module which I built in order to parse DOS variables. It will be the subject of my next post.