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?
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.
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.
array.max_by do |element| element.field end
Or:
array.max_by(&:field)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With