我有像这样的哈希
{ 55 => {:value=>61, :rating=>-147},
89 => {:value=>72, :rating=>-175},
78 => {:value=>64, :rating=>-155},
84 => {:value=>90, :rating=>-220},
95 => {:value=>39, :rating=>-92},
46 => {:value=>97, :rating=>-237},
52 => {:value=>73, :rating=>-177},
64 => {:value=>69, :rating=>-167},
86 => {:value=>68, :rating=>-165},
53 => {:value=>20, :rating=>-45}
}
如何按 :评分 对其进行排序?或者我应该使用一些不同的结构?
答案 0 :(得分:6)
我会将数据结构更改为哈希数组:
my_array =
[
{:id => 78, :value=>64, :rating=>-155},
{:id => 84, :value=>90, :rating=>-220},
{:id => 95, :value=>39, :rating=>-92}
]
您可以使用
轻松对这种结构进行排序my_array.sort_by { |record| record[:rating] }
要获得通过id获取记录的类似哈希的功能,您可以在my_array上定义一个新方法:
def my_array.find_by_id(id)
self.find { |hash| hash[:id] == id }
end
所以在那之后你可以做到
my_array.find_by_id(id)
而不是
my_hash[id]
答案 1 :(得分:5)
Ruby中的哈希值无法排序(至少不在1.9之前)
这意味着循环哈希不一定会以正确的顺序为您提供信息。但是,通过首先将其转换为数组,以特定顺序循环遍历Hashed数据是微不足道的,事实上,在Hash上调用sort方法会将它转换为数组:
>> { :a => 4, :b => 12, :c => 3, :d => 8 }.sort_by { |key, value| value }
=> [[:c, 3], [:a, 4], [:d, 8], [:b, 12]]
所以在你的情况下:
hsh.sort_by {|key, ratings| ratings[:rating] }
答案 2 :(得分:3)
可能有一个更好的数据结构,但(我假设这是红宝石)可以通过使用内联排序样式在Ruby中基本上告诉它如何比较这两者。这是一个具体的例子:
my_hash = {
55 => {:value=>61, :rating=>-147},
89 => {:value=>72, :rating=>-175},
78 => {:value=>64, :rating=>-155},
84 => {:value=>90, :rating=>-220},
95 => {:value=>39, :rating=>-92},
46 => {:value=>97, :rating=>-237},
52 => {:value=>73, :rating=>-177},
64 => {:value=>69, :rating=>-167},
86 => {:value=>68, :rating=>-165},
53 => {:value=>20, :rating=>-45}
}
puts "MY HASH"
my_hash.each do |local|
puts local
end
sorted_hash = my_hash.sort { | leftval, rightval | rightval[1][:rating]<=>leftval[1][:rating] }
puts "SORTED HASH"
sorted_hash.each do |local|
puts local
end