Hash ordered in the way it was created

61 Views Asked by At

I need a hash key-value pairs to be in the same order as I have assigned. Created Hash in Ruby 1.8:

tmp = {}
tmp["name"] = "laxman"
tmp["age"] = "25"
tmp["city"] = "pune"
tmp # => {"city"=>"pune", "name"=>"laxman", "age"=>"25"}

I need the output:

tmp # => {"name"=>"laxman", "age"=>"25","city"=>"pune"}

Please advise.

1

There are 1 best solutions below

2
Simone Carletti On BEST ANSWER

Starting from Ruby 1.9 the Hash preserves the order of the keys.

However, if you are using an older version or if for whatever reason the behavior doesn't satisfy you, it's fairly easy to create a custom OrderedHash type that relies on an Array to keep the order of the keys and on a Hash as a storage.

ActiveSupport was used to provide an implementation back in the days where it supported Ruby < 2.0. You can find it here.