How to find a min/max with Ruby
You can do
[5, 10].min
or
[4, 7].max
They come from the Enumerable module, so anything that includes Enumerable
will have those methods available.
v2.4 introduces own Array#min
and Array#max
, which are way faster than Enumerable's methods because they skip calling #each
.
@nicholasklick mentions another option, Enumerable#minmax
, but this time returning an array of [min, max]
.
[4, 5, 7, 10].minmax=> [4, 10]
All those results generate garbage in a zealous attempt to handle more than two arguments. I'd be curious to see how they perform compared to good 'ol:
def max (a,b) a>b ? a : bend
which is, by-the-way, my official answer to your question.