Method: Array#max

Defined in:
array.c

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

Returns one of the following:

  • The maximum-valued element from self.

  • A new array of maximum-valued elements from self.

Does not modify self.

With no block given, each element in self must respond to method #<=> with a numeric.

With no argument and no block, returns the element in self having the maximum value per method #<=>:

[1, 0, 3, 2].max # => 3

With non-negative numeric argument count and no block, returns a new array with at most count elements, in descending order, per method #<=>:

[1, 0, 3, 2].max(3)   # => [3, 2, 1]
[1, 0, 3, 2].max(3.0) # => [3, 2, 1]
[1, 0, 3, 2].max(9)   # => [3, 2, 1, 0]
[1, 0, 3, 2].max(0)   # => []

With a block given, the block must return a numeric.

With a block and no argument, calls the block self.size - 1 times to compare elements; returns the element having the maximum value per the block:

['0', '', '000', '00'].max {|a, b| a.size <=> b.size }
# => "000"

With non-negative numeric argument count and a block, returns a new array with at most count elements, in descending order, per the block:

['0', '', '000', '00'].max(2) {|a, b| a.size <=> b.size }
# => ["000", "00"]

Related: see Methods for Fetching.

Overloads:

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

    Yields:

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

    Yields:

    • (a, b)


6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
# File 'array.c', line 6021

static VALUE
rb_ary_max(int argc, VALUE *argv, VALUE ary)
{
    VALUE result = Qundef, v;
    VALUE num;
    long i;

    if (rb_check_arity(argc, 0, 1) && !NIL_P(num = argv[0]))
       return rb_nmin_run(ary, num, 0, 1, 1);

    const long n = RARRAY_LEN(ary);
    if (rb_block_given_p()) {
        for (i = 0; i < RARRAY_LEN(ary); i++) {
           v = RARRAY_AREF(ary, i);
           if (UNDEF_P(result) || rb_cmpint(rb_yield_values(2, v, result), v, result) > 0) {
               result = v;
           }
        }
    }
    else if (n > 0) {
        result = RARRAY_AREF(ary, 0);
        if (n > 1) {
            if (FIXNUM_P(result) && CMP_OPTIMIZABLE(INTEGER)) {
                return ary_max_opt_fixnum(ary, 1, result);
            }
            else if (STRING_P(result) && CMP_OPTIMIZABLE(STRING)) {
                return ary_max_opt_string(ary, 1, result);
            }
            else if (RB_FLOAT_TYPE_P(result) && CMP_OPTIMIZABLE(FLOAT)) {
                return ary_max_opt_float(ary, 1, result);
            }
            else {
                return ary_max_generic(ary, 1, result);
            }
        }
    }
    if (UNDEF_P(result)) return Qnil;
    return result;
}