method
max
v2_5_5 -
Show latest stable
- Class:
Array
max(p1 = v1)public
Returns the object in ary with the maximum value. The first form assumes all objects implement Comparable; the second uses the block to return a <=> b.
ary = %w(albatross dog horse) ary.max #=> "horse" ary.max { |a, b| a.length <=> b.length } #=> "albatross"
If the n argument is given, maximum n elements are returned as an array.
ary = %w[albatross dog horse] ary.max (2) #=> ["horse", "dog"] ary.max (2) {|a, b| a.length <=> b.length } #=> ["albatross", "horse"]
static VALUE
rb_ary_max(int argc, VALUE *argv, VALUE ary)
{
struct cmp_opt_data cmp_opt = { 0, 0 };
VALUE result = Qundef, v;
VALUE num;
long i;
rb_scan_args(argc, argv, "01", &num);
if (!NIL_P(num))
return rb_nmin_run(ary, num, 0, 1, 1);
if (rb_block_given_p()) {
for (i = 0; i < RARRAY_LEN(ary); i++) {
v = RARRAY_AREF(ary, i);
if (result == Qundef || rb_cmpint(rb_yield_values(2, v, result), v, result) > 0) {
result = v;
}
}
}
else {
for (i = 0; i < RARRAY_LEN(ary); i++) {
v = RARRAY_AREF(ary, i);
if (result == Qundef || OPTIMIZED_CMP(v, result, cmp_opt) > 0) {
result = v;
}
}
}
if (result == Qundef) return Qnil;
return result;
}