Ruby 维护哈希插入顺序

发布于 2024-11-29 01:27:21 字数 684 浏览 2 评论 0原文

我正在寻找一种方法来维护我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

傲鸠 2024-12-06 01:27:21

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.

◇流星雨 2024-12-06 01:27:21

您可以在包含最初排序顺序的键的一侧保留一个列表

hash = {}
keys = []

在插入时:

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

按插入顺序迭代:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文