Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More concise version of max/min without the block

Tags:

ruby

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?

like image 414
wersimmon Avatar asked Nov 28 '22 10:11

wersimmon


2 Answers

This is more concise:

['abc', 'defg'].max_by{|x| x.length }
like image 20
David Grayson Avatar answered Dec 23 '22 08:12

David Grayson


['abcd', 'def'].max_by &:length
like image 199
DigitalRoss Avatar answered Dec 23 '22 07:12

DigitalRoss