wersimmon
wersimmon

Reputation: 2869

More concise version of max/min without the block

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?

Upvotes: 4

Views: 1235

Answers (3)

Nolan Amy
Nolan Amy

Reputation: 11135

For an array of Hashes:

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

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

=> 25

Upvotes: 0

DigitalRoss
DigitalRoss

Reputation: 146133

['abcd', 'def'].max_by &:length

Upvotes: 15

David Grayson
David Grayson

Reputation: 87486

This is more concise:

['abc', 'defg'].max_by{|x| x.length }

Upvotes: 9

Related Questions