如何根据散列中的值从数组中获取散列?

如何根据哈希值中的数组从数组中获取哈希? 在这种情况下,我想选择得分最低的哈希值,即potato 。 我使用Ruby 1.9。

 [ { name: "tomato", score: 9 }, { name: "potato", score: 3 }, { name: "carrot", score: 6 } ] 

您可以使用Enumerable的min_by方法:

 ary.min_by {|h| h[:score] } #=> { name: "potato", score: "3" } 

我认为你的意图是按数字而不是字符串进行比较。

 array.min_by{|h| h[:score].to_i} 

编辑由于OP改变了问题,答案就变成了

 array.min_by{|h| h[:score]} 

现在与Zach Kemp的回答毫无区别。

Ruby的Enumerable#min_by绝对是要走的路; 但是,只是为了踢,这里是一个基于Enumerable#reduce的解决方案:

 array.reduce({}) do |memo, x| min_score = memo[:score] (!min_score || (min_score > x[:score])) ? x : memo end