Richard Stokes
Richard Stokes

Reputation: 3552

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

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?

Upvotes: 94

Views: 62055

Answers (3)

Linju
Linju

Reputation: 335

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

Upvotes: 3

David Grayson
David Grayson

Reputation: 87386

array.max_by do |element|
  element.field
end

Or:

array.max_by(&:field)

Upvotes: 169

p.matsinopoulos
p.matsinopoulos

Reputation: 7810

Does this help?

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

(I assume that your field has name attr)

Upvotes: 29

Related Questions