I am a beginner in Ruby and I came across a code snippet which had the following:
def add(*nums)
nums.inject(&:+)
end
Examples:
add(1, 2)
#=> 3
add(1, 2, 3, 4)
#=> 10
How does the code snippet work?
I am a beginner in Ruby and I came across a code snippet which had the following:
def add(*nums)
nums.inject(&:+)
end
Examples:
add(1, 2)
#=> 3
add(1, 2, 3, 4)
#=> 10
How does the code snippet work?
As specified in the doc: https://apidock.com/ruby/Enumerable/inject
inject
:
Combines all elements of enum by applying a binary operation, specified by a block or a symbol that names a method or operator.
You can use it with enumerable(array, range, ..)
like this,
[1, 2, 3].inject { |sum, number| sum + number }
or short-hand style,
[1, 2, 3].inject(&:+)
If you're wondering about this (&:+)
and how it works, check this also,
In the docs it says it works like:
# Same using a block and inject
(5..10).inject { |sum, n| sum + n } #=> 45
https://ruby-doc.org/core-2.4.2/Enumerable.html#method-i-inject
Eg. It is summing up 1,2,3,4 which equals 10
As I have done so in this answer, print each step using puts
to see what's going on:
def add(*nums)
nums.inject { |sum, element|
puts "",
"sum is #{sum} and element is #{element}",
"new sum is #{sum} + #{element} = #{sum + element}",
"-" * 25
sum + element
}
end
add(1, 2, 3, 4)
#sum is 1 and element is 2
#new sum is 1 + 2 = 3
#-------------------------
#sum is 3 and element is 3
#new sum is 3 + 3 = 6
#-------------------------
#sum is 6 and element is 4
#new sum is 6 + 4 = 10
#-------------------------
#=> 10