Ruby 维护哈希插入顺序
我正在寻找一种方法来维护我在 Ruby 中使用的哈希的插入顺序。我的数据来自数据库,并且已经按照我想要的方式分组/排序,但 Ruby 不保证在我的版本 1.8.4
中保持哈希中的顺序。
有什么解决方法吗?如果没有,我可以创建自定义比较器吗?
这是哈希:
{
"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]
}
任何想法都会很棒, 谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Ruby 自版本 1.9(2007 年 12 月发布)起维护哈希顺序(请参阅:http://www.igvita.com/2009/02/04/ruby-19-internals-ordered-hash/)
此外,还有一个名为 orderedhash 适用于较旧的红宝石。
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.
您可以在包含最初排序顺序的键的一侧保留一个列表
:
在插入时:
按插入顺序迭代:
You can keep a list on the side containing the keys in sorted order
initially:
on insert:
to iterate in insertion order: