4

I normally do ['abc', 'defg'].max{|a, b| a.length <=> b.length}, but this seems like a lot of extra typing to compare the results of the same method on both objects.

Is there a more concise way, to do something like ['abc', 'defg'].max(:length), which would run a given method on each object for the comparison?

wersimmon
  • 2,809
  • 3
  • 22
  • 35

3 Answers3

15
['abcd', 'def'].max_by &:length
DigitalRoss
  • 143,651
  • 25
  • 248
  • 329
9

This is more concise:

['abc', 'defg'].max_by{|x| x.length }
David Grayson
  • 84,103
  • 24
  • 152
  • 189
0

For an array of Hashes:

roomies = [{:name => "Habib", :age => 24}, {:name => "Tyler", :age => 25}]

roomies.max_by{|a| a[:age]}[:age]

=> 25
Nolan Amy
  • 10,785
  • 5
  • 34
  • 45