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

Looking at how to calculate the factorial of a number, I came across this code:

(1..5).inject(:*) || 1 # => 120 

What does (:*) || 1 (:*) || 1 ?

How it compares with this line of code (1..5).inject(1) { |x, y| x * y } # => 120 (1..5).inject(1) { |x, y| x * y } # => 120 , which uses .inject to achieve similar functionality?

+4
source share
3 answers

Colon-star alone means nothing in Ruby. It is just a symbol , and you can pass an inject enumerated symbol. This character names the method or operator that will be used for the elements of an enumerable.

For example:

 (1..5).inject(:*) #=> 1 * 2 * 3 * 4 * 5 = 120 (1..5).inject(:+) #=> 1 + 2 + 3 + 4 + 5 = 15 

Part || 1 || 1 means that if inject returns falsey , 1 used instead. (Which in your example will never happen.)

+15
source

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 the method name as a character, it can be called via send. This is what injections and friends do.

About || if the left side returns nil or false, lhs || 1 lhs || 1 will return 1

+3
source

This is exactly the same. You can use each method to your liking.

+2
source

Source: https://habr.com/ru/post/1481099/


All Articles