Method: Enumerable#min

Defined in:
enum.c

#minObject #min(n) ⇒ Array #min {|a, b| ... } ⇒ Object #min(n) {|a, b| ... } ⇒ Array

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 }                          # => []

Related: #min_by, #minmax, #max.

Overloads:

  • #min(n) ⇒ Array

    Returns:

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

    Yields:

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

    Yields:

    • (a, b)

    Returns:



2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
# File 'enum.c', line 2376

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;
}