instance method
Enumerable#max_by
() -> ::Enumerator[Elem, Elem?]
() { (Elem arg0) -> (::Comparable | ::Array[untyped]) } -> Elem?
(::Integer arg0) -> ::Enumerator[Elem, ::Array[Elem]]
(::Integer arg0) { (Elem arg0) -> (::Comparable | ::Array[untyped]) } -> ::Array[Elem]
max_by {|element| ... } → element
max_by(n) {|element| ... } → array
max_by → enumerator
max_by(n) → enumerator
enum.c
View on GitHub ↗
static VALUE
enum_max_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, 1, 0);
memo = MEMO_NEW(Qundef, Qnil, 0);
rb_block_call(obj, id_each, 0, 0, max_by_i, (VALUE)memo);
return memo->v2;
}
Returns the elements for which the block returns the maximum values.
With a block given and no argument, returns the element for which the block returns the maximum value:
Example
(1..4).max_by {|element| -element } # => 1 %w[a b c d].max_by {|element| -element.ord } # => "a" {foo: 0, bar: 1, baz: 2}.max_by {|key, value| -value } # => [:foo, 0] [].max_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 maximum values:
Example
(1..4).max_by(2) {|element| -element } # => [1, 2] %w[a b c d].max_by(2) {|element| -element.ord } # => ["a", "b"] {foo: 0, bar: 1, baz: 2}.max_by(2) {|key, value| -value } # => [[:foo, 0], [:bar, 1]] [].max_by(2) {|element| -element } # => []
Returns an Enumerator if no block is given.