Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does ":*" (colon-star) mean in Ruby?

Tags:

ruby

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?

like image 375
Gray Kemmey Avatar asked Dec 01 '22 03:12

Gray Kemmey


2 Answers

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.)

like image 176
Mischa Avatar answered Dec 15 '22 13:12

Mischa


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

like image 41
nurettin Avatar answered Dec 15 '22 13:12

nurettin