哈希按其创建方式排序

Hash ordered in the way it was created

我需要一个散列键值对,其顺序与我指定的顺序相同。在 Ruby 1.8:

中创建哈希
tmp = {}
tmp["name"] = "laxman"
tmp["age"] = "25"
tmp["city"] = "pune"
tmp # => {"city"=>"pune", "name"=>"laxman", "age"=>"25"}

我需要输出:

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

请指教

从 Ruby 1.9 开始,Hash 保留了键的顺序。

但是,如果您使用的是旧版本,或者如果出于某种原因该行为不满足您的要求,则创建依赖于 Array 的自定义 OrderedHash 类型相当容易保持键的顺序并放在Hash上作为存储。

ActiveSupport 在支持 Ruby < 2.0 的日子里被用来提供一个实现。 You can find it here.