查找具有特定属性最大值的 Ruby 数组元素 [英] Finding the element of a Ruby array with the maximum value for a particular attribute
本文介绍了查找具有特定属性最大值的 Ruby 数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这个问题可能有一个非常简单的答案,但我目前无法弄清楚.如果我有一个特定类型对象的 ruby 数组,并且它们都有一个特定的字段,我如何找到该字段具有最大值的数组元素?
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?
推荐答案
array.max_by do |element|
element.field
end
或者:
array.max_by(&:field)
这篇关于查找具有特定属性最大值的 Ruby 数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文