<分区>
我正在编写一种计算数字阶乘的方法,我在搜索中发现了类似的东西。
def factorial(number)
(1..number).inject(:*) || 1
end
它有效,我明白注入(inject)函数在做什么,但我不清楚 (:\*)
部分的真正含义。
我知道它一定是写作 {|num, prod| 的简写版本num*prod}
,但我希望有一个明确的解释。谢谢!!
标签 ruby
<分区>
我正在编写一种计算数字阶乘的方法,我在搜索中发现了类似的东西。
def factorial(number)
(1..number).inject(:*) || 1
end
它有效,我明白注入(inject)函数在做什么,但我不清楚 (:\*)
部分的真正含义。
我知道它一定是写作 {|num, prod| 的简写版本num*prod}
,但我希望有一个明确的解释。谢谢!!
最佳答案
:*
只是 inject
执行方法的 *
的方法名。如果您查看 inject
的文档 http://ruby-doc.org/core-2.2.2/Enumerable.html#method-i-inject
它指出
If you specify a symbol instead, then each element in the collection will be passed to the named method of memo. In either case, the result becomes the new value for memo. At the end of the iteration, the final value of memo is the return value for the method.
所以采用 inject { |memo, obj| block
以下是相等的
ary = [1,2,3]
ary.inject(:*)
#=> 6
ary.inject { |memo, obj| memo.*(obj) }
#=> 6
关于ruby - 我正在学习 Ruby,我不清楚 :* means in inject(:*) 是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30356668/