End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
Enumerable#minmax
enum.minmax → [min, max]
enum.minmax { |a, b| block } → [min, max]
enum.c
View on GitHub ↗
static VALUE
enum_minmax(VALUE obj)
{
VALUE memo;
struct minmax_t *m = NEW_CMP_OPT_MEMO(struct minmax_t, memo);
m->min = Qundef;
m->last = Qundef;
m->cmp_opt.opt_methods = 0;
m->cmp_opt.opt_inited = 0;
if (rb_block_given_p()) {
rb_block_call(obj, id_each, 0, 0, minmax_ii, memo);
if (m->last != Qundef)
minmax_ii_update(m->last, m->last, m);
}
else {
rb_block_call(obj, id_each, 0, 0, minmax_i, memo);
if (m->last != Qundef)
minmax_i_update(m->last, m->last, m);
}
if (m->min != Qundef) {
return rb_assoc_new(m->min, m->max);
}
return rb_assoc_new(Qnil, Qnil);
}
Returns a two element array which contains the minimum and the maximum value in the enumerable. The first form assumes all objects implement <=>; the second uses the block to return a <=> b.
Example
a = %w(albatross dog horse) a.minmax #=> ["albatross", "horse"] a.minmax { |a, b| a.length <=> b.length } #=> ["dog", "albatross"]