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}
a more complete but longer/harder version

8 comments
Comments feed for this article
2009-10-07 at 7:46:37
Tyler Rick
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.
2010-01-15 at 11:08:00
Sébastien Grosjean - ZenCocoon
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.
2010-01-15 at 12:38:00
Sébastien Grosjean - ZenCocoon
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
2010-01-15 at 12:46:20
pragmatig
First solution it shorter, but imo not simpler.
The second solution looks edge-case-complete afaik.
2010-01-15 at 13:27:11
Sébastien Grosjean - ZenCocoon
Right, it’s simpler not easier. Anyone shall use the one he prefer
Both makes the job.
2010-01-15 at 13:28:23
Sébastien Grosjean - ZenCocoon
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
2010-01-26 at 16:24:37
Brian
Instead of
ActiveSupport::OrderedHash.new [[1,2]]
use
ActiveSupport::OrderedHash[1,2]
2010-01-26 at 20:17:09
pragmatig
Thanks for the tip, i added it to the post!