### 如何排序不是简单的哈希（散列哈希）

``````{ 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}
}
``````

#### 3 个答案:

``````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] }
``````

``````def my_array.find_by_id(id)
self.find { |hash| hash[:id] == id }
end
``````

``````my_array.find_by_id(id)
``````

``````my_hash[id]
``````

Ruby中的哈希值无法排序（至少不在1.9之前）

``````>> { :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] }
``````

``````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
``````