Returns the result of applying a reducer to an initial value and the first element of the Enumerable
. It then takes the result and applies the function to it and the second element of the collection, and so on. The return value is the result returned by the final call to the function.
You can think of
[ a, b, c, d ].inject(i) { |r, v| fn(r, v) }
as being
fn(fn(fn(fn(i, a), b), c), d)
In a way the inject
function injects the function between the elements of the enumerable.
inject
is aliased as reduce
. You use it when you want to reduce a collection to a single value.
The Calling Sequences
Let’s start with the most verbose:
enum.inject(initial_value) do |result, next_value| # do something with +result+ and +next_value+ # the value returned by the block becomes the # value passed in to the next iteration # as +result+ end
For example:
product = [ 2, 3, 4 ].inject(1) do |result, next_value| result * next_value end product #=> 24
When this runs, the block is first called with 1
(the initial value) and 2
(the first element of the array). The block returns 1*2
, so on the next iteration the block is called with 2
(the previous result) and 3
. The block returns 6
, and is called one last time with 6
and 4
. The result of the block, 24
becomes the value returned by inject
. This code returns the product of the elements in the enumerable.
First Shortcut: Default Initial value
In the case of the previous example, the initial value, 1
, wasn’t really necessary: the calculation of the product of a list of numbers is self-contained.
In these circumstances, you can omit the initial_value
parameter. inject
will then initially call the block with the first element of the collection as the result
parameter and the second element as the next_value
.
[ 2, 3, 4 ].inject do |result, next_value| result * next_value end
This shortcut is convenient, but can only be used when the block produces a result which can be passed back to it as a first parameter.
Here’s an example where that’s not the case: it returns a hash where the keys are words and the values are the number of occurrences of that word in the enumerable.
freqs = File.read("README.md") .scan(/\w{2,}/) .reduce(Hash.new(0)) do |counts, word| counts[word] += 1 counts end freqs #=> {"Actions"=>4, "Status"=>5, "MinGW"=>3, "https"=>27, "github"=>10, "com"=>15, ...
Note that the last line of the block is just the word counts
. This ensures the return value of the block is the result that’s being calculated.
Second Shortcut: a Reducer function
A reducer function is a function that takes a partial result and the next value, returning the next partial result. The block that is given to inject
is a reducer.
You can also write a reducer as a function and pass the name of that function (as a symbol) to inject
. However, for this to work, the function
Must be defined on the type of the result value
Must accept a single parameter, the next value in the collection, and
Must return an updated result which will also implement the function.
Here’s an example that adds elements to a string. The two calls invoke the functions String#concat
and String#+
on the result so far, passing it the next value.
s = [ "cat", " ", "dog" ].inject("", :concat) s #=> "cat dog" s = [ "cat", " ", "dog" ].inject("The result is:", :+) s #=> "The result is: cat dog"
Here’s a more complex example when the result object maintains state of a different type to the enumerable elements.
class Turtle def initialize @x = @y = 0 end def move(dir) case dir when "n" then @y += 1 when "s" then @y -= 1 when "e" then @x += 1 when "w" then @x -= 1 end self end end position = "nnneesw".chars.reduce(Turtle.new, :move) position #=>> #<Turtle:0x00000001052f4698 @y=2, @x=1>
Third Shortcut: Reducer With no Initial Value
If your reducer returns a value that it can accept as a parameter, then you don’t have to pass in an initial value. Here :*
is the name of the times function:
product = [ 2, 3, 4 ].inject(:*) product # => 24
String
concatenation again:
s = [ "cat", " ", "dog" ].inject(:+) s #=> "cat dog"
And an example that converts a hash to an array of two-element subarrays.
nested = {foo: 0, bar: 1}.inject([], :push) nested # => [[:foo, 0], [:bar, 1]]
Returns whether for any element object == element
:
(1..4).include?(2) # => true (1..4).include?(5) # => false (1..4).include?('2') # => false %w[a b c d].include?('b') # => true %w[a b c d].include?('2') # => false {foo: 0, bar: 1, baz: 2}.include?(:foo) # => true {foo: 0, bar: 1, baz: 2}.include?('foo') # => false {foo: 0, bar: 1, baz: 2}.include?(0) # => false
Returns an enumerator object generated from this enumerator and given enumerables.
e = (1..3).chain([4, 5]) e.to_a #=> [1, 2, 3, 4, 5]
Returns true if coverage stats are currently being collected (after Coverage.start
call, but before Coverage.result
call)
Returns the short user name of the currently logged in user. Unfortunately, it is often rather easy to fool ::getlogin
.
Avoid ::getlogin
for security-related purposes.
If ::getlogin
fails, try ::getpwuid
.
See the unix manpage for getpwuid(3)
for more detail.
e.g.
Etc.getlogin -> 'guest'
Allocate size
bytes of memory and return the integer memory address for the allocated memory.
Decompresses string
. Raises a Zlib::NeedDict
exception if a preset dictionary is needed for decompression.
This method is almost equivalent to the following code:
def inflate(string) zstream = Zlib::Inflate.new buf = zstream.inflate(string) zstream.finish zstream.close buf end
See also Zlib.deflate
Returns true
if filepath
points to a symbolic link, false
otherwise:
symlink = File.symlink('t.txt', 'symlink') File.symlink?('symlink') # => true File.symlink?('t.txt') # => false
Invokes the block with a Benchmark::Report object, which may be used to collect and report on the results of individual benchmark tests. Reserves label_width
leading spaces for labels on each line. Prints caption
at the top of the report, and uses format
to format each line. (Note: caption
must contain a terminating newline character, see the default Benchmark::Tms::CAPTION for an example.)
Returns an array of Benchmark::Tms
objects.
If the block returns an array of Benchmark::Tms
objects, these will be used to format additional lines of output. If labels
parameter are given, these are used to label these extra lines.
Note: Other methods provide a simpler interface to this one, and are suitable for nearly all benchmarking requirements. See the examples in Benchmark
, and the bm
and bmbm
methods.
Example:
require 'benchmark' include Benchmark # we need the CAPTION and FORMAT constants n = 5000000 Benchmark.benchmark(CAPTION, 7, FORMAT, ">total:", ">avg:") do |x| tf = x.report("for:") { for i in 1..n; a = "1"; end } tt = x.report("times:") { n.times do ; a = "1"; end } tu = x.report("upto:") { 1.upto(n) do ; a = "1"; end } [tf+tt+tu, (tf+tt+tu)/3] end
Generates:
user system total real for: 0.970000 0.000000 0.970000 ( 0.970493) times: 0.990000 0.000000 0.990000 ( 0.989542) upto: 0.970000 0.000000 0.970000 ( 0.972854) >total: 2.930000 0.000000 2.930000 ( 2.932889) >avg: 0.976667 0.000000 0.976667 ( 0.977630)
Invokes the block with a Benchmark::Report object, which may be used to collect and report on the results of individual benchmark tests. Reserves label_width
leading spaces for labels on each line. Prints caption
at the top of the report, and uses format
to format each line. (Note: caption
must contain a terminating newline character, see the default Benchmark::Tms::CAPTION for an example.)
Returns an array of Benchmark::Tms
objects.
If the block returns an array of Benchmark::Tms
objects, these will be used to format additional lines of output. If labels
parameter are given, these are used to label these extra lines.
Note: Other methods provide a simpler interface to this one, and are suitable for nearly all benchmarking requirements. See the examples in Benchmark
, and the bm
and bmbm
methods.
Example:
require 'benchmark' include Benchmark # we need the CAPTION and FORMAT constants n = 5000000 Benchmark.benchmark(CAPTION, 7, FORMAT, ">total:", ">avg:") do |x| tf = x.report("for:") { for i in 1..n; a = "1"; end } tt = x.report("times:") { n.times do ; a = "1"; end } tu = x.report("upto:") { 1.upto(n) do ; a = "1"; end } [tf+tt+tu, (tf+tt+tu)/3] end
Generates:
user system total real for: 0.970000 0.000000 0.970000 ( 0.970493) times: 0.990000 0.000000 0.990000 ( 0.989542) upto: 0.970000 0.000000 0.970000 ( 0.972854) >total: 2.930000 0.000000 2.930000 ( 2.932889) >avg: 0.976667 0.000000 0.976667 ( 0.977630)
The path where gem executables are to be installed.
The path were rubygems plugins are to be installed.
Top level install helper method. Allows you to install gems interactively:
% irb >> Gem.install "minitest" Fetching: minitest-5.14.0.gem (100%) => [#<Gem::Specification:0x1013b4528 @name="minitest", ...>]
Returns the currently set formatter. By default, it is set to DidYouMean::Formatter
.
Updates the primary formatter used to format the suggestions.
Copies a file entry. See install(1).
Arguments src
(a single path or an array of paths) and dest
(a single path) should be interpretable as paths;
If the entry at dest
does not exist, copies from src
to dest
:
File.read('src0.txt') # => "aaa\n" File.exist?('dest0.txt') # => false FileUtils.install('src0.txt', 'dest0.txt') File.read('dest0.txt') # => "aaa\n"
If dest
is a file entry, copies from src
to dest
, overwriting:
File.read('src1.txt') # => "aaa\n" File.read('dest1.txt') # => "bbb\n" FileUtils.install('src1.txt', 'dest1.txt') File.read('dest1.txt') # => "aaa\n"
If dest
is a directory entry, copies from src
to dest/src
, overwriting if necessary:
File.read('src2.txt') # => "aaa\n" File.read('dest2/src2.txt') # => "bbb\n" FileUtils.install('src2.txt', 'dest2') File.read('dest2/src2.txt') # => "aaa\n"
If src
is an array of paths and dest
points to a directory, copies each path path
in src
to dest/path
:
File.file?('src3.txt') # => true File.file?('src3.dat') # => true FileUtils.mkdir('dest3') FileUtils.install(['src3.txt', 'src3.dat'], 'dest3') File.file?('dest3/src3.txt') # => true File.file?('dest3/src3.dat') # => true
Keyword arguments:
group: group
- changes the group if not nil
, using File.chown
.
mode: permissions
- changes the permissions. using File.chmod
.
noop: true
- does not copy entries; returns nil
.
owner: owner
- changes the owner if not nil
, using File.chown
.
preserve: true
- preserve timestamps using File.utime
.
verbose: true
- prints an equivalent command:
FileUtils.install('src0.txt', 'dest0.txt', noop: true, verbose: true) FileUtils.install('src1.txt', 'dest1.txt', noop: true, verbose: true) FileUtils.install('src2.txt', 'dest2', noop: true, verbose: true)
Output:
install -c src0.txt dest0.txt install -c src1.txt dest1.txt install -c src2.txt dest2
Related: methods for copying.
Copies a file entry. See install(1).
Arguments src
(a single path or an array of paths) and dest
(a single path) should be interpretable as paths;
If the entry at dest
does not exist, copies from src
to dest
:
File.read('src0.txt') # => "aaa\n" File.exist?('dest0.txt') # => false FileUtils.install('src0.txt', 'dest0.txt') File.read('dest0.txt') # => "aaa\n"
If dest
is a file entry, copies from src
to dest
, overwriting:
File.read('src1.txt') # => "aaa\n" File.read('dest1.txt') # => "bbb\n" FileUtils.install('src1.txt', 'dest1.txt') File.read('dest1.txt') # => "aaa\n"
If dest
is a directory entry, copies from src
to dest/src
, overwriting if necessary:
File.read('src2.txt') # => "aaa\n" File.read('dest2/src2.txt') # => "bbb\n" FileUtils.install('src2.txt', 'dest2') File.read('dest2/src2.txt') # => "aaa\n"
If src
is an array of paths and dest
points to a directory, copies each path path
in src
to dest/path
:
File.file?('src3.txt') # => true File.file?('src3.dat') # => true FileUtils.mkdir('dest3') FileUtils.install(['src3.txt', 'src3.dat'], 'dest3') File.file?('dest3/src3.txt') # => true File.file?('dest3/src3.dat') # => true
Keyword arguments:
group: group
- changes the group if not nil
, using File.chown
.
mode: permissions
- changes the permissions. using File.chmod
.
noop: true
- does not copy entries; returns nil
.
owner: owner
- changes the owner if not nil
, using File.chown
.
preserve: true
- preserve timestamps using File.utime
.
verbose: true
- prints an equivalent command:
FileUtils.install('src0.txt', 'dest0.txt', noop: true, verbose: true) FileUtils.install('src1.txt', 'dest1.txt', noop: true, verbose: true) FileUtils.install('src2.txt', 'dest2', noop: true, verbose: true)
Output:
install -c src0.txt dest0.txt install -c src1.txt dest1.txt install -c src2.txt dest2
Related: methods for copying.