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.
Starting from Ruby 1.9 the
Hashpreserves 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
OrderedHashtype that relies on anArrayto keep the order of the keys and on aHashas a storage.ActiveSupportwas used to provide an implementation back in the days where it supported Ruby < 2.0. You can find it here.