The simple
ActiveSupport::OrderedHash.new [[1,2]]
does no longer work in Rails 2.3, so I built a small patch for array that make OrderedHash creation simple again.
Code
class Array def to_ordered_hash ActiveSupport::OrderedHash[self] end end
Usage
hash = [[:key, 'value'], [:key2, :value2], [1, 2]].to_ordered_hash hash == {:key=>'value', :key2=>:value2, :1=>2}
Thanks for this tip! I was very confused when I tried to instantiate a new hash with ActiveSupport::OrderedHash.new the same way I had done before only to get back an empty hash! Adding Array#to_ordered_hash makes instantiation so much nicer. I wish they would add that to core Ruby or Rails.
Nice one, you can simplify your method like :
def to_ordered_hash
returning(ActiveSupport::OrderedHash.new){|map| each {|k,v| map[k] = v } }
end
Hope that helps.
An other useful tool I’ve just made to I18n-js :
http://seb.box.re/2010/1/15/convert-hash-to-ordered-hash-with-rails-2-3-and-ruby-1-8
First solution it shorter, but imo not simpler.
The second solution looks edge-case-complete afaik.
Right, it’s simpler not easier. Anyone shall use the one he prefer 😉 Both makes the job.
I found your nice post and snippet while working on ordering hash with ruby 1.8 and rails 2.3+.
I’ve came up with the following at : http://seb.box.re/2010/1/15/deep-hash-ordering-with-ruby-1-8
Might be a useful tool
Instead of
ActiveSupport::OrderedHash.new [[1,2]]
use
ActiveSupport::OrderedHash[1,2]
Thanks for the tip, i added it to the post!