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?
-
possible duplicate of More concise version of max/min without the block – Andrew Grimm Nov 7 '11 at 22:05
array.max_by do |element|
element.field
end
Or:
array.max_by(&:field)
-
Check the documentation of the Enumerable module for more helpful methods. – David Grayson Nov 7 '11 at 16:05
Does this help?
my_array.max {|a,b| a.attr <=> b.attr }
(I assume that your field has name attr
)
-
Yes that is exactly what I was looking for, was scouring the Array api and couldn't find anything, forget to check the api for Enumberable, thanks! – Richard Stokes Nov 7 '11 at 16:04
-
1Always check the Enumerable API. It has everything you need and the kitchen sink! – Sahil Muthoo Nov 7 '11 at 16:05
-
2I prefer using
max_by
because it is simpler to use: the block only takes a single argument and you don't have to explicitly use the spaceship (<=>
) operator. – David Grayson Nov 7 '11 at 23:03 -
@DavidGrayson Thanks for the info. I didn't know the existence of this method. I will vote up on your comment and answer. – p.matsinopoulos Nov 8 '11 at 8:47
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"]
-
2If you're just going for minimum or maximum, the algorithms are
O(n)
. Sorting is by minimumO(n log n)
. Don't use this unless you need to, as there are some unnecessary performance losses. – Jamie Oct 31 '17 at 10:24 -
1True. Sorting is an overkill just to get max. I added this in case someone wants to get 2nd largest, 3rd largest etc. – Linju Aug 6 '18 at 9:19