Enumerable#inject
--Method for performing convolution operationReference: https://docs.ruby-lang.org/ja/latest/method/Enumerable/i/inject.html
module
. A mix-in for repeating classes. The following are famous friends (instance methods).
map
find
select
Reference: https://docs.ruby-lang.org/ja/latest/class/Enumerable.html
In Ruby, thanks to the ʻEnumerable` module, you can use methods with convenient iterations.
ary = [1,2,3,4,5]
ary.inject(1){ |sum, n| sum + n }
# => 16
--The return value of each process in the block is in sum
.
--The method argument goes into the initial value (the block argument of the first process).
--Repeat until the last element, and the return value of the last block becomes the total return value.
,,,Hard to understand.
Let's make it easy to understand.
ary = [1,2,3,4,5]
ary.inject(1) do |sum, n|
puts sum
sum + n
end
=begin
=>1 (Initial value specified in the argument of inject"1"Enters sum)
=>2 (Initial value (sum)+Sum of the first element (n) of the array)
=>4 (The return value (2) of the previous process is in sum+Second element sum)
=>7 (Omitted below)
=>11
=>16 (overall return value)
=end
Can you imagine it somehow? This is ** folding **.
By the way, if you omit the method argument (hoge
part of ʻinject (hoge)`), the first element of the array will be set to the initial value.
ary = [1,2,3,4,5]
ary.inject do |sum, n|
puts sum
sum + n
end
=begin
=>1
=>3
=>6
=>10
=>15 (overall return value)
=end
With a proper understanding, you can write complex processes in an easy-to-understand manner. Since the processing inside the block can be repeated by folding, it can be written shorter than the ʻeach` method.
In other words, it is often used for refactoring iterations.
Let's write some practical code below.
sum = 0
ary = [100,200,300,42,52]
ary.each { |n| sum += n }
puts sum
# =>694
ary = [100,200,300,42,52]
sum = ary.inject { |s, n| s += n }
puts sum
# =>694
One line has decreased. Refreshing.
Recommended Posts