Array.to_ordered_hash replacement for Rails 2.3 ActiveSupport::OrderedHash.new

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

Advertisements

8 thoughts on “Array.to_ordered_hash replacement for Rails 2.3 ActiveSupport::OrderedHash.new

  1. 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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s