这个 ruby 注入魔法是如何工作的? [英] How does this ruby injection magic work?
本文介绍了这个 ruby 注入魔法是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我今天看到了一个 ruby 代码片段.
I saw a ruby code snippet today.
[1,2,3,4,5,6,7].inject(:+)
<代码>=>28
[1,2,3,4,5,6,7].inject(:*)
<代码>=>5040
这里的注入和我以前见过的完全不同,比如
The injection here is quite different from those I've seen before, like
[1,2,3,4,5,6,7].inject {|sum, x| sum + x}
请解释它是如何工作的?
Please explain how does it work?
推荐答案
没有魔法,符号(方法)只是可能的参数之一.这是来自文档:
There's no magic, symbol (method) is just one of the possible parameters. This is from the docs:
# enum.inject(initial, sym) => obj
# enum.inject(sym) => obj
# enum.inject(initial) {| memo, obj | block } => obj
# enum.inject {| memo, obj | block } => obj
我们的案例是第二个.
你也可以用传统块重写:
You can also rewrite it with traditional block:
op = :+ # parameter of inject call
[1,2,3,4,5,6,7].inject {|sum, x| sum.send(op, x)} # also returns 28
(回答它是如何工作的"部分)
(to answer "how does it work" part)
这篇关于这个 ruby 注入魔法是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文