Finding a Ruby array element with a maximum value for a specific attribute

Probably a very simple answer to this question, but I can’t let this figure out in my life at the moment. If I have a ruby ​​array of a certain type of objects and they all have a specific field, how can I find the element of the array that has the highest value for this field?

+54
ruby
Nov 07 '11 at 16:00
source share
3 answers
array.max_by do |element| element.field end 

Or:

 array.max_by(&:field) 
+110
Nov 07 2018-11-11T00:
source share
β€” -

Does it help?

 my_array.max {|a,b| a.attr <=> b.attr } 

(I assume your field is named attr )

+23
Nov 07 2018-11-11T00:
source share

You can also sort the array and then get the maximum, minimum, second largest value, etc.

 array = array.sort_by {|k,v| v}.reverse puts hash[0]["key"] 
0
Mar 28 '16 at 23:43
source share



All Articles