Looking up how to calculate the factorial of a number I came across this code:
(1..5).inject(:*) || 1 # => 120
What is the (:*) || 1
doing?
How does it compare to this line of code (1..5).inject(1) { |x, y| x * y } # => 120
, which uses .inject
to achieve similar functionality?
Colon-star in itself doesn't mean anything in Ruby. It's just a symbol and you can pass a symbol to the inject
method of an enumerable. That symbol names a method or operator to be used on the elements of the enumerable.
So e.g.:
(1..5).inject(:*) #=> 1 * 2 * 3 * 4 * 5 = 120
(1..5).inject(:+) #=> 1 + 2 + 3 + 4 + 5 = 15
The || 1
part means that if inject
returns a falsey value, 1
is used instead. (Which in your example will never happen.)
test.rb:
def do_stuff(binary_function)
2.send(binary_function, 3)
end
p do_stuff(:+)
p do_stuff(:*)
$ ruby test.rb
5
6
If you pass a method name as a symbol, it can be called via send. This is what inject and friends are doing.
About the ||
part, in case the left hand side returns nil or false, lhs || 1
will return 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With