End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
Array#min
static VALUE
rb_ary_min(int argc, VALUE *argv, VALUE ary)
{
struct cmp_opt_data cmp_opt = { 0, 0 };
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, 0, 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 (result == Qundef || 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(cmp_opt, Integer)) {
return ary_min_opt_fixnum(ary, 1, result);
}
else if (STRING_P(result) && CMP_OPTIMIZABLE(cmp_opt, String)) {
return ary_min_opt_string(ary, 1, result);
}
else if (RB_FLOAT_TYPE_P(result) && CMP_OPTIMIZABLE(cmp_opt, Float)) {
return ary_min_opt_float(ary, 1, result);
}
else {
return ary_min_generic(ary, 1, result);
}
}
}
if (result == Qundef) return Qnil;
return result;
}
Returns one of the following:
-
The minimum-valued element from
self. -
A new Array of minimum-valued elements selected from
self.
When no block is given, each element in self must respond to method <=> with an Integer.
With no argument and no block, returns the element in self having the minimum value per method <=>:
[0, 1, 2].min # => 0
With Integer argument n and no block, returns a new Array with at most n elements, in ascending order per method <=>:
[0, 1, 2, 3].min(3) # => [0, 1, 2] [0, 1, 2, 3].min(6) # => [0, 1, 2, 3]
When a block is given, the block must return an Integer.
With a block and no argument, calls the block self.size-1 times to compare elements; returns the element having the minimum value per the block:
['0', '00', '000'].min { |a, b| a.size <=> b.size } # => "0"
With an argument n and a block, returns a new Array with at most n elements, in ascending order per the block:
[0, 1, 2, 3].min(3) # => [0, 1, 2] [0, 1, 2, 3].min(6) # => [0, 1, 2, 3]