这个问题可能有一个非常简单的答案,但我无论如何也想不出来。如果我有一个特定类型对象的红宝石数组,并且它们都有一个特定的字段,那么如何找到该字段值最大的数组元素呢?
Does this help?
my_array.max {|a,b| a.attr <=> b.attr }
(I assume that your field has name attr)
attr
array.max_by do |element| element.field end
Or:
array.max_by(&:field)
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"]