94

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?

Richard Stokes
  • 3,532
  • 7
  • 41
  • 57
  • possible duplicate of [More concise version of max/min without the block](http://stackoverflow.com/questions/7087717/more-concise-version-of-max-min-without-the-block) – Andrew Grimm Nov 07 '11 at 22:05

3 Answers3

169
array.max_by do |element|
  element.field
end

Or:

array.max_by(&:field)
David Grayson
  • 84,103
  • 24
  • 152
  • 189
29

Does this help?

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

(I assume that your field has name attr)

p.matsinopoulos
  • 7,655
  • 6
  • 44
  • 92
  • 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 07 '11 at 16:04
  • 1
    Always check the Enumerable API. It has everything you need *and* the kitchen sink! – Sahil Muthoo Nov 07 '11 at 16:05
  • 2
    I 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 07 '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 08 '11 at 08:47
3

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"]
Linju
  • 335
  • 3
  • 9
  • 2
    If you're just going for minimum or maximum, the algorithms are `O(n)`. Sorting is by minimum `O(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
  • 1
    True. Sorting is an overkill just to get max. I added this in case someone wants to get 2nd largest, 3rd largest etc. – Linju Aug 06 '18 at 09:19