Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
Enumerable#min
static VALUE
enum_min(int argc, VALUE *argv, VALUE obj)
{
VALUE memo;
struct min_t *m = NEW_MEMO_FOR(struct min_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, 0, 0);
m->min = Qundef;
if (rb_block_given_p()) {
rb_block_call(obj, id_each, 0, 0, min_ii, memo);
}
else {
rb_block_call(obj, id_each, 0, 0, min_i, memo);
}
result = m->min;
if (UNDEF_P(result)) return Qnil;
return result;
}
Returns the element with the minimum 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 minimum element, using the elements’ own method <=> for comparison:
(1..4).min # => 1 (-4..-1).min # => -4 %w[d c b a].min # => "a" {foo: 0, bar: 1, baz: 2}.min # => [:bar, 1] [].min # => nil
With positive integer argument n given, and no block, returns an array containing the first n minimum elements that exist:
(1..4).min(2) # => [1, 2] (-4..-1).min(2) # => [-4, -3] %w[d c b a].min(2) # => ["a", "b"] {foo: 0, bar: 1, baz: 2}.min(2) # => [[:bar, 1], [:baz, 2]] [].min(2) # => []
With a block given, the block determines the minimum 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 minimum element as determined by the block:
%w[xxx x xxxx xx].min {|a, b| a.size <=> b.size } # => "x" h = {foo: 0, bar: 1, baz: 2} h.min {|pair1, pair2| pair1[1] <=> pair2[1] } # => [:foo, 0] [].min {|a, b| a <=> b } # => nil
With a block given and positive integer argument n given, returns an array containing the first n minimum elements that exist, as determined by the block.
%w[xxx x xxxx xx].min(2) {|a, b| a.size <=> b.size } # => ["x", "xx"] h = {foo: 0, bar: 1, baz: 2} h.min(2) {|pair1, pair2| pair1[1] <=> pair2[1] } # => [[:foo, 0], [:bar, 1]] [].min(2) {|a, b| a <=> b } # => []