End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
Enumerable#max
enum.max → obj
enum.max { |a, b| block } → obj
enum.max(n) → array
enum.max(n) { |a, b| block } → array
enum.c
View on GitHub ↗
static VALUE
enum_max(int argc, VALUE *argv, VALUE obj)
{
VALUE memo;
struct max_t *m = NEW_CMP_OPT_MEMO(struct max_t, memo);
VALUE result;
VALUE num;
if (rb_check_arity(argc, 0, 1) && !NIL_P(num = argv[0]))
return rb_nmin_run(obj, num, 0, 1, 0);
m->max = 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, max_ii, (VALUE)memo);
}
else {
rb_block_call(obj, id_each, 0, 0, max_i, (VALUE)memo);
}
result = m->max;
if (result == Qundef) return Qnil;
return result;
}
Returns the object in enum with the maximum value. The first form assumes all objects implement <=>; the second uses the block to return a <=> b.
Example
a = %w(albatross dog horse) a.max #=> "horse" a.max { |a, b| a.length <=> b.length } #=> "albatross"
If the n argument is given, maximum n elements are returned as an array, sorted in descending order.
Example
a = %w[albatross dog horse] a.max(2) #=> ["horse", "dog"] a.max(2) {|a, b| a.length <=> b.length } #=> ["albatross", "horse"] [5, 1, 3, 4, 2].max(3) #=> [5, 4, 3]