iCoreTech Research Labs Just a placeholder

25Aug/090

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

Related posts:

  1. jGrowl on Rails (with i18n)
  2. Send SMS with Ruby on Rails
  3. Rails users < membership > groups? Enter Workflow
  4. Installing MySQL Ruby Gem in Snow Leopard Server
  5. Passenger (mod_rails) $PATH on Leopard / Snow Leopard

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.

Additional comments powered by BackType