Ruby Tuesday – Enumerable#max

Today’s Ruby function in Enumerable#max.

Enumerable#max will find the largest item in an enum of items that are Comparable.

This means it works against numbers, strings, symbols, or more, as long as that type includes the module Comparable.

[5, 67, 30, 102, 3, 1].max
#=> 102
['baz', 'bar', 'foo', 'xray', 'z', 'a'].max
#=> "z"
[:foo, :bar, :baz, :snafu].max
#=> :snafu

Enumerable#max can also take a block of two arguments, allowing you to find the max based off of another property of those objects, such as the length:

['baz', 'bar', 'foo', 'xray', 'z', 'a'].max {|a, b| a.length <=> b.length}
=> "xray"


Leave a Reply

Your email address will not be published. Required fields are marked *