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?
什么是(:*)|| 1做什么?
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?
它与这行代码(1..5)相比如何.inject(1){| x,y | x * y}#=> 120,它使用.inject来实现类似的功能?
3 个解决方案
#1
15
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.
冒号星本身并不代表Ruby中的任何东西。它只是一个符号,您可以将符号传递给可枚举的注入方法。该符号命名要在可枚举元素上使用的方法或运算符。
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.)
|| 1部分表示如果inject返回falsey值,则使用1。 (在你的例子中哪个永远不会发生。)
#2
3
test.rb:
test.rb:
def do_stuff(binary_function)
2.send(binary_function, 3)
end
p do_stuff(:+)
p do_stuff(:*)
$ ruby test.rb
$ ruby test.rb
5
五
6
6
If you pass a method name as a symbol, it can be called via send. This is what inject and friends are doing.
如果将方法名称作为符号传递,则可以通过send调用它。这是注入和朋友正在做的事情。
About the ||
part, in case the left hand side returns nil or false, lhs || 1
will return 1
关于||部分,如果左侧返回nil或false,lhs || 1将返回1
#3
2
It's absolutely equal. You may use each way, up to your taste.
这绝对是平等的。您可以根据自己的喜好使用各种方式。
#1
15
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.
冒号星本身并不代表Ruby中的任何东西。它只是一个符号,您可以将符号传递给可枚举的注入方法。该符号命名要在可枚举元素上使用的方法或运算符。
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.)
|| 1部分表示如果inject返回falsey值,则使用1。 (在你的例子中哪个永远不会发生。)
#2
3
test.rb:
test.rb:
def do_stuff(binary_function)
2.send(binary_function, 3)
end
p do_stuff(:+)
p do_stuff(:*)
$ ruby test.rb
$ ruby test.rb
5
五
6
6
If you pass a method name as a symbol, it can be called via send. This is what inject and friends are doing.
如果将方法名称作为符号传递,则可以通过send调用它。这是注入和朋友正在做的事情。
About the ||
part, in case the left hand side returns nil or false, lhs || 1
will return 1
关于||部分,如果左侧返回nil或false,lhs || 1将返回1
#3
2
It's absolutely equal. You may use each way, up to your taste.
这绝对是平等的。您可以根据自己的喜好使用各种方式。