查找具有特定属性最大值的 Ruby 数组元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8038993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding the element of a Ruby array with the maximum value for a particular attribute
提问by Richard Stokes
There is probably a very simple answer to this question, but I can't for the life of me figure it out at the moment. If I have a ruby array of a certain type of objects, and they all have a particular field, how do I find the element of the array the has the largest value for that field?
这个问题可能有一个非常简单的答案,但我目前无法弄清楚。如果我有一个特定类型对象的 ruby 数组,并且它们都有一个特定的字段,我如何找到该字段具有最大值的数组元素?
回答by David Grayson
array.max_by do |element|
element.field
end
Or:
或者:
array.max_by(&:field)
回答by p.matsinopoulos
Does this help?
这有帮助吗?
my_array.max {|a,b| a.attr <=> b.attr }
(I assume that your field has name attr)
(我假设你的领域有 name attr)
回答by Linju
You can also sort the array and then get max, min, second largest value etc.
您还可以对数组进行排序,然后获得最大值、最小值、第二大值等。
array = array.sort_by {|k,v| v}.reverse
puts hash[0]["key"]

