ruby - 我正在学习 Ruby,我不清楚 :* means in inject(:*) 是什么

标签 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/

相关文章:

ruby - 弹出不可预知的模态对话框后,如何继续 Cucumber 步骤?

ruby - 如何在 ruby​​ 数组中找到匹配值?

ruby - 在 Ruby 中,执行存储在字符串中的本地 Linux 命令的最佳方法是什么?

ruby - 删除重复字符的正则表达式

ruby-on-rails - 如何在Rails中将 "3.days"转换成字符串 "3 days"?

Ruby 安装导致终端以 cat 方式打开

ruby - 用ruby生成一系列特殊字符

ruby-on-rails - tinymce 所见即所得编辑器在 html 中提供了额外的行

ruby - 究竟什么是 gem native 扩展?

ruby - :each - how to do on one line instead of do. .end block 之前的 rspec?