Ruby maintain Hash insertion order

心已入冬 提交于 2019-12-04 03:55:16

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

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.

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