0005 Minmax

We thought we knew them, but we discovered some subtleties!

These functions are defined in the Enumerable module, which is included in Array as well as Hash, Range, Enumerator, Struct, …

0005-minmax_1.png

The <=> method is used for comparison. Elements must be comparable, otherwise an exception is thrown. The comparison can be parameterized with a block. In this case, it is often convenient to use min_by / max_by.

0005-minmax_2.png

These methods can be used with an argument to obtain the n smallest/largest elements. There’s even a minmax method!

0005-minmax_3.png

⚠️ Beware of Range limitations.

0005-minmax_4.png

Links to Ruby documentation for min, max, min_by, max_by, minmax et minmax_by.