Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the element of a Ruby array with the maximum value for a particular attribute

Tags:

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?

like image 260
Richard Stokes Avatar asked Nov 07 '11 16:11

Richard Stokes


People also ask

How do you find the max value of an attribute in an array object?

Maximum value of an attribute in an array of objects can be searched in two ways, one by traversing the array and the other method is by using the Math. max. apply() method.

How do you find the highest element in an array?

To find the largest element from the array, a simple way is to arrange the elements in ascending order. After sorting, the first element will represent the smallest element, the next element will be the second smallest, and going on, the last element will be the largest element of the array.


1 Answers

array.max_by do |element|   element.field end 

Or:

array.max_by(&:field) 
like image 120
David Grayson Avatar answered Sep 20 '22 16:09

David Grayson