End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
Enumerable#min_by
enum.min_by {|obj| block } → obj
enum.min_by → an_enumerator
enum.min_by(n) {|obj| block } → array
enum.min_by(n) → an_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 object in enum that gives the minimum value from the given block.
If no block is given, an enumerator is returned instead.
Example
a = %w(albatross dog horse) a.min_by { |x| x.length } #=> "dog"
If the n argument is given, minimum n elements are returned as an array. These n elements are sorted by the value from the given block.
Example
a = %w[albatross dog horse] p a.min_by(2) {|x| x.length } #=> ["dog", "horse"]