Ruby ordered hash tip with Rails

This is quite old, as many of you ruby coders knows that ruby 1.8 doesn’t keep a Hash ordered, while 1.9 does.

This is seldom necessary however, there are bit of codes where it’s important to have the Hash keep the order:

# ruby 1.8.7
>> {:a => "a", :c => "c", :b => "b"}
=> {:b => "b", :c => "c", :a => "a"}
# ruby 1.9.1
>> {:a => "a", :c => "c", :b => "b"}
=> {:a => "a", :c => "c", :b => "b"}

If then you’re using Rails and Ruby 1.8, instead of relying on some kind of black magic sorting by keys or values you can access directly the namespaced ActiveSupport::OrderedHash like this:

1
2
3
4
5
  def build_recurring_hash
    returning(ActiveSupport::OrderedHash.new) do |map|
      (1..5).each{ |n| map[n] = n }
    end
  end
$1.99 domains with SSL purchase!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">