0

1)我有一个哈希,在 ruby​​ 控制台中编码

influencerHash

influencerHash.class => Hash

{"inf3"=>{"followingCount"=>256, "followersCount"=>80, "name"=>"Branislav Seslija", "score"=>10.4099998474121}, "inf2"=>{"followingCount"=>6, "followersCount"=>4, "name"=>"Greg Seslija", "score"=>29.8400001525879}, "inf1"=>{"followingCount"=>13, "followersCount"=>10, "name"=>"Amit Kumar", "score"=>30.6499996185303}}

2)我对其进行了排序,但哈希被转换为数组

sortHash = influencerHash.sort

sortHash.class => Array

[["inf1", {"followingCount"=>13, "followersCount"=>10, "name"=>"Amit Kumar", "score"=>30.6499996185303}], ["inf2", {"followingCount"=>6, "followersCount"=>4, "name"=>"Greg Seslija", "score"=>29.8400001525879}], ["inf3", {"followingCount"=>256, "followersCount"=>80, "name"=>"Branislav Seslija", "score"=>10.4099998474121}]]

3)我将它转换回哈希,但排序的结果是相反的(见上面的数组和下面的哈希结果)

sortHash = Hash[influencerHash.sort]

sortHash.class => Hash

{"inf3"=>{"followingCount"=>256, "followersCount"=>80, "name"=>"Branislav Seslija", "score"=>10.4099998474121}, "inf2"=>{"followingCount"=>6, "followersCount"=>4, "name"=>"Greg Seslija", "score"=>29.8400001525879}, "inf1"=>{"followingCount"=>13, "followersCount"=>10, "name"=>"Amit Kumar", "score"=>30.6499996185303}}

**

为什么会发生这种情况,我将如何获得与 Array 中相同但作为 Hash 的排序?

**

4

1 回答 1

0

看来您使用的是 Ruby 1.9 之前的版本,其中不存在具有顺序的 Hash 元素的概念。

如果你真的需要有序哈希,并且如果你真的不能升级到 Ruby 1.9,那么有一些库可以为旧版本的 Ruby 实现有序哈希。(例如Hashery等。)

如果可能的话,我建议升级到 Ruby 1.9。

于 2012-07-05T10:56:22.400 回答