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
, …
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
.
These methods can be used with an argument to obtain the n smallest/largest elements. There’s even a minmax
method!
⚠️ Beware of Range
limitations.
Links to Ruby documentation for min
, max
, min_by
, max_by
, minmax
et minmax_by
.