End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
Enumerable#min_by
min_by {|element| ... } → element
min_by(n) {|element| ... } → array
min_by → enumerator
min_by(n) → enumerator
enum.c
View on GitHub ↗
static VALUE
enum_min_by(int argc, VALUE *argv, VALUE obj)
{
struct MEMO *memo;
VALUE num;
rb_check_arity(argc, 0, 1);
RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_size);
if (argc && !NIL_P(num = argv[0]))
return rb_nmin_run(obj, num, 1, 0, 0);
memo = MEMO_NEW(Qundef, Qnil, 0);
rb_block_call(obj, id_each, 0, 0, min_by_i, (VALUE)memo);
return memo->v2;
}
Returns the elements for which the block returns the minimum values.
With a block given and no argument, returns the element for which the block returns the minimum value:
Example
(1..4).min_by {|element| -element } # => 4 %w[a b c d].min_by {|element| -element.ord } # => "d" {foo: 0, bar: 1, baz: 2}.min_by {|key, value| -value } # => [:baz, 2] [].min_by {|element| -element } # => nil
With a block given and positive integer argument n given, returns an array containing the n elements for which the block returns minimum values:
Example
(1..4).min_by(2) {|element| -element } # => [4, 3] %w[a b c d].min_by(2) {|element| -element.ord } # => ["d", "c"] {foo: 0, bar: 1, baz: 2}.min_by(2) {|key, value| -value } # => [[:baz, 2], [:bar, 1]] [].min_by(2) {|element| -element } # => []
Returns an Enumerator if no block is given.