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

Ruby

Ruby Problem Overview


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?

Ruby Solutions


Solution 1 - Ruby

array.max_by do |element|
  element.field
end

Or:

array.max_by(&:field)

Solution 2 - Ruby

Does this help?

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

(I assume that your field has name attr)

Solution 3 - Ruby

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"]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRichard StokesView Question on Stackoverflow
Solution 1 - RubyDavid GraysonView Answer on Stackoverflow
Solution 2 - Rubyp.matsinopoulosView Answer on Stackoverflow
Solution 3 - RubyLinjuView Answer on Stackoverflow