Method: Enumerable#max

Defined in:
enum.c

#maxObject #max(n) ⇒ Array #max {|a, b| ... } ⇒ Object #max(n) {|a, b| ... } ⇒ Array

Returns the element with the maximum element according to a given criterion. The ordering of equal elements is indeterminate and may be unstable.

With no argument and no block, returns the maximum element, using the elements’ own method #<=> for comparison:

(1..4).max                   # => 4
(-4..-1).max                 # => -1
%w[d c b a].max              # => "d"
{foo: 0, bar: 1, baz: 2}.max # => [:foo, 0]
[].max                       # => nil

With positive integer argument n given, and no block, returns an array containing the first n maximum elements that exist:

(1..4).max(2)                   # => [4, 3]
(-4..-1).max(2)                # => [-1, -2]
%w[d c b a].max(2)              # => ["d", "c"]
{foo: 0, bar: 1, baz: 2}.max(2) # => [[:foo, 0], [:baz, 2]]
[].max(2)                       # => []

With a block given, the block determines the maximum elements. The block is called with two elements a and b, and must return:

  • A negative integer if a < b.

  • Zero if a == b.

  • A positive integer if a > b.

With a block given and no argument, returns the maximum element as determined by the block:

%w[xxx x xxxx xx].max {|a, b| a.size <=> b.size } # => "xxxx"
h = {foo: 0, bar: 1, baz: 2}
h.max {|pair1, pair2| pair1[1] <=> pair2[1] }     # => [:baz, 2]
[].max {|a, b| a <=> b }                          # => nil

With a block given and positive integer argument n given, returns an array containing the first n maximum elements that exist, as determined by the block.

%w[xxx x xxxx xx].max(2) {|a, b| a.size <=> b.size } # => ["xxxx", "xxx"]
h = {foo: 0, bar: 1, baz: 2}
h.max(2) {|pair1, pair2| pair1[1] <=> pair2[1] }
# => [[:baz, 2], [:bar, 1]]
[].max(2) {|a, b| a <=> b }                          # => []

Related: #min, #minmax, #max_by.

Overloads:

  • #max(n) ⇒ Array

    Returns:

  • #max {|a, b| ... } ⇒ Object

    Yields:

    • (a, b)
  • #max(n) {|a, b| ... } ⇒ Array

    Yields:

    • (a, b)

    Returns:



2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
# File 'enum.c', line 2498

static VALUE
enum_max(int argc, VALUE *argv, VALUE obj)
{
    VALUE memo;
    struct max_t *m = NEW_MEMO_FOR(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;
    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 (UNDEF_P(result)) return Qnil;
    return result;
}