Ruby maintain Hash insertion order

冷暖自知 提交于 2019-12-21 09:20:10

问题


I am looking for a way to maintain the insert order for a Hash that I am using in Ruby. My data is coming from a database and is already grouped/ordered the way I want it, but Ruby doesn't guarantee maintained order in Hashs in my version 1.8.4.

Is there any workaround for this? If not is there a way I could create a custom comparator?

Here is the Hash:

{
"February"=>[0.5667, 14.6834, 79.7666, 261.8668, 342.1167, 723.517], 
"March"=>[0.0, 26.4667, 554.45, 681.3164, 2376.0668, 10353.0358], 
"May"=>[2.75, 34.6666, 342.1831, 1331.8999, 1589.617, 9282.9662], 
"July"=>[1.9, 2.3666, 59.45, 302.1501, 554.1652, 5195.0839], 
"June"=>[0.15, 24.2166, 244.1498, 335.6834, 536.067, 1498.949], 
"August"=>[0.0, 0.4, 9.3668, 30.7164, 67.7504, 162.0337], 
"April"=>[0.0, 8.3, 68.9331, 357.9168, 815.9662, 2870.217]
 }

Any ideas would be great, Thanks


回答1:


You can keep a list on the side containing the keys in sorted order

initially:

hash = {}
keys = []

on insert:

def insert(key, value)
  keys << key unless hash[key]
  hash[key] = value
end

to iterate in insertion order:

for key in keys do
  puts key, hash[key]
end



回答2:


Ruby since version 1.9 (released dec 2007) maintains Hash order (see: http://www.igvita.com/2009/02/04/ruby-19-internals-ordered-hash/)

Also, there is a gem for this called orderedhash for older Rubies.



来源:https://stackoverflow.com/questions/7040617/ruby-maintain-hash-insertion-order

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!