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:
(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:
(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.
Returns one of the following:
The maximum-valued element from self
.
A new Array
of maximum-valued elements selected from self
.
When no block is given, each element in self
must respond to method <=>
with an Integer
.
With no argument and no block, returns the element in self
having the maximum value per method <=>
:
[0, 1, 2].max # => 2
With an argument Integer
n
and no block, returns a new Array
with at most n
elements, in descending order per method <=>
:
[0, 1, 2, 3].max(3) # => [3, 2, 1] [0, 1, 2, 3].max(6) # => [3, 2, 1, 0]
When a block is given, the block must return an Integer
.
With a block and no argument, calls the block self.size-1
times to compare elements; returns the element having the maximum value per the block:
['0', '00', '000'].max {|a, b| a.size <=> b.size } # => "000"
With an argument n
and a block, returns a new Array
with at most n
elements, in descending order per the block:
['0', '00', '000'].max(2) {|a, b| a.size <=> b.size } # => ["000", "00"]
Returns the maximum value in self
, using method <=>
or a given block for comparison.
With no argument and no block given, returns the maximum-valued element of self
.
(1..4).max # => 4 ('a'..'d').max # => "d" (-4..-1).max # => -1
With non-negative integer argument n
given, and no block given, returns the n
maximum-valued elements of self
in an array:
(1..4).max(2) # => [4, 3] ('a'..'d').max(2) # => ["d", "c"] (-4..-1).max(2) # => [-1, -2] (1..4).max(50) # => [4, 3, 2, 1]
If a block is given, it is called:
First, with the first two element of self
.
Then, sequentially, with the so-far maximum value and the next element of self
.
To illustrate:
(1..4).max {|a, b| p [a, b]; a <=> b } # => 4
Output:
[2, 1] [3, 2] [4, 3]
With no argument and a block given, returns the return value of the last call to the block:
(1..4).max {|a, b| -(a <=> b) } # => 1
With non-negative integer argument n
given, and a block given, returns the return values of the last n
calls to the block in an array:
(1..4).max(2) {|a, b| -(a <=> b) } # => [1, 2] (1..4).max(50) {|a, b| -(a <=> b) } # => [1, 2, 3, 4]
Returns an empty array if n
is zero:
(1..4).max(0) # => [] (1..4).max(0) {|a, b| -(a <=> b) } # => []
Returns nil
or an empty array if:
The begin value of the range is larger than the end value:
(4..1).max # => nil (4..1).max(2) # => [] (4..1).max {|a, b| -(a <=> b) } # => nil (4..1).max(2) {|a, b| -(a <=> b) } # => []
The begin value of an exclusive range is equal to the end value:
(1...1).max # => nil (1...1).max(2) # => [] (1...1).max {|a, b| -(a <=> b) } # => nil (1...1).max(2) {|a, b| -(a <=> b) } # => []
Raises an exception if either:
self
is a endless range: (1..)
.
A block is given and self
is a beginless range.
Related: Range#min
, Range#minmax
.
Returns the element with the maximum 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 maximum element, using the elements’ own method <=>
for comparison:
(1..4).max # => 4 (-4..-1).max # => -1 %w[d c b a].max # => "d" {foo: 0, bar: 1, baz: 2}.max # => [:foo, 0] [].max # => nil
With positive integer argument n
given, and no block, returns an array containing the first n
maximum elements that exist:
(1..4).max(2) # => [4, 3] (-4..-1).max(2) # => [-1, -2] %w[d c b a].max(2) # => ["d", "c"] {foo: 0, bar: 1, baz: 2}.max(2) # => [[:foo, 0], [:baz, 2]] [].max(2) # => []
With a block given, the block determines the maximum 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 maximum element as determined by the block:
%w[xxx x xxxx xx].max {|a, b| a.size <=> b.size } # => "xxxx" h = {foo: 0, bar: 1, baz: 2} h.max {|pair1, pair2| pair1[1] <=> pair2[1] } # => [:baz, 2] [].max {|a, b| a <=> b } # => nil
With a block given and positive integer argument n
given, returns an array containing the first n
maximum elements that exist, as determined by the block.
%w[xxx x xxxx xx].max(2) {|a, b| a.size <=> b.size } # => ["xxxx", "xxx"] h = {foo: 0, bar: 1, baz: 2} h.max(2) {|pair1, pair2| pair1[1] <=> pair2[1] } # => [[:baz, 2], [:bar, 1]] [].max(2) {|a, b| a <=> b } # => []
Returns the maximum size of the queue.
Sets the maximum number of times to retry an idempotent request in case of Net::ReadTimeout, IOError
, EOFError
, Errno::ECONNRESET, Errno::ECONNABORTED, Errno::EPIPE, OpenSSL::SSL::SSLError
, Timeout::Error
. The initial value is 1.
Argument retries
must be a non-negative numeric value:
http = Net::HTTP.new(hostname) http.max_retries = 2 # => 2 http.max_retries # => 2
Sets the upper bound of the supported SSL/TLS protocol version. See min_version=
for the possible values.
Returns a 2-element array containing the elements for which the block returns minimum and maximum values:
(1..4).minmax_by {|element| -element } # => [4, 1] %w[a b c d].minmax_by {|element| -element.ord } # => ["d", "a"] {foo: 0, bar: 1, baz: 2}.minmax_by {|key, value| -value } # => [[:baz, 2], [:foo, 0]] [].minmax_by {|element| -element } # => [nil, nil]
Returns an Enumerator
if no block is given.
This integer returns the maximum level of data structure nesting in the generated JSON
, max_nesting
= 0 if no maximum is checked.
This sets the maximum level of data structure nesting in the generated JSON
to the integer depth, max_nesting
= 0 if no maximum should be checked.
With a block given, returns an array of elements of self
, sorted according to the value returned by the block for each element. The ordering of equal elements is indeterminate and may be unstable.
Examples:
a = %w[xx xxx x xxxx] a.sort_by {|s| s.size } # => ["x", "xx", "xxx", "xxxx"] a.sort_by {|s| -s.size } # => ["xxxx", "xxx", "xx", "x"] h = {foo: 2, bar: 1, baz: 0} h.sort_by{|key, value| value } # => [[:baz, 0], [:bar, 1], [:foo, 2]] h.sort_by{|key, value| key } # => [[:bar, 1], [:baz, 0], [:foo, 2]]
With no block given, returns an Enumerator
.
The current implementation of sort_by
generates an array of tuples containing the original collection element and the mapped value. This makes sort_by
fairly expensive when the keysets are simple.
require 'benchmark' a = (1..100000).map { rand(100000) } Benchmark.bm(10) do |b| b.report("Sort") { a.sort } b.report("Sort by") { a.sort_by { |a| a } } end
produces:
user system total real Sort 0.180000 0.000000 0.180000 ( 0.175469) Sort by 1.980000 0.040000 2.020000 ( 2.013586)
However, consider the case where comparing the keys is a non-trivial operation. The following code sorts some files on modification time using the basic sort
method.
files = Dir["*"] sorted = files.sort { |a, b| File.new(a).mtime <=> File.new(b).mtime } sorted #=> ["mon", "tues", "wed", "thurs"]
This sort is inefficient: it generates two new File
objects during every comparison. A slightly better technique is to use the Kernel#test
method to generate the modification times directly.
files = Dir["*"] sorted = files.sort { |a, b| test(?M, a) <=> test(?M, b) } sorted #=> ["mon", "tues", "wed", "thurs"]
This still generates many unnecessary Time
objects. A more efficient technique is to cache the sort keys (modification times in this case) before the sort. Perl users often call this approach a Schwartzian transform, after Randal Schwartz. We construct a temporary array, where each element is an array containing our sort key along with the filename. We sort this array, and then extract the filename from the result.
sorted = Dir["*"].collect { |f| [test(?M, f), f] }.sort.collect { |f| f[1] } sorted #=> ["mon", "tues", "wed", "thurs"]
This is exactly what sort_by
does internally.
sorted = Dir["*"].sort_by { |f| test(?M, f) } sorted #=> ["mon", "tues", "wed", "thurs"]
To produce the reverse of a specific order, the following can be used:
ary.sort_by { ... }.reverse!
With a block given returns a hash:
Each key is a return value from the block.
Each value is an array of those elements for which the block returned that key.
Examples:
g = (1..6).group_by {|i| i%3 } g # => {1=>[1, 4], 2=>[2, 5], 0=>[3, 6]} h = {foo: 0, bar: 1, baz: 0, bat: 1} g = h.group_by {|key, value| value } g # => {0=>[[:foo, 0], [:baz, 0]], 1=>[[:bar, 1], [:bat, 1]]}
With no block given, returns an Enumerator
.
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:
(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:
(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.
Makes the set compare its elements by their identity and returns self. This method may not be supported by all subclasses of Set
.
Returns true if the set will compare its elements by their identity. Also see Set#compare_by_identity
.
Sets self
to consider only identity in comparing keys; two keys are considered the same only if they are the same object; returns self
.
By default, these two object are considered to be the same key, so s1
will overwrite s0
:
s0 = 'x' s1 = 'x' h = {} h.compare_by_identity? # => false h[s0] = 0 h[s1] = 1 h # => {"x"=>1}
After calling #compare_by_identity, the keys are considered to be different, and therefore do not overwrite each other:
h = {} h.compare_by_identity # => {} h.compare_by_identity? # => true h[s0] = 0 h[s1] = 1 h # => {"x"=>0, "x"=>1}
Returns true
if compare_by_identity
has been called, false
otherwise.
Creates an option from the given parameters params
. See Parameters for New Options.
The block, if given, is the handler for the created option. When the option is encountered during command-line parsing, the block is called with the argument given for the option, if any. See Option Handlers.
Defines options which set in to options for keyword parameters of method.
Parameters for each keywords are given as elements of params.
Fetches the engine as specified by the id String
.
OpenSSL::Engine.by_id("openssl") => #<OpenSSL::Engine id="openssl" name="Software engine support">
See OpenSSL::Engine.engines
for the currently loaded engines.
If the stream begins with a BOM (byte order marker), consumes the BOM and sets the external encoding accordingly; returns the result encoding if found, or nil
otherwise:
File.write('t.tmp', "\u{FEFF}abc") io = File.open('t.tmp', 'rb') io.set_encoding_by_bom # => #<Encoding:UTF-8> io.close File.write('t.tmp', 'abc') io = File.open('t.tmp', 'rb') io.set_encoding_by_bom # => nil io.close
Raises an exception if the stream is not binmode or its encoding has already been set.
Sets the encoding according to the BOM (Byte Order Mark) in the string.
Returns self
if the BOM is found, otherwise +nil.
Removes the gemspec matching full_name
from the dependency list
Find
the best specification matching a name
and requirements
. Raises if the dependency doesn’t resolve to a valid specification.