是否有任何额外的注入速记 [英] are there any additional inject shorthand

查看:46
本文介绍了是否有任何额外的注入速记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到了这个问题:
我一直像这样使用注入(我知道 (0) 部分是可选的,可以省略)

I recently ran into this issue:
I've always used inject like so (i knew that (0) part is optional and can be omitted)

array = [13,23,13]
#=> [13, 23, 13]
array.inject(0) { |sum,i| sum+i }
#=> 49

我偶然发现你可以使用:

By chance i found out that you can use:

array.inject(:+)
#=> 49
array.inject(:-)
#=> -23
array.inject(:*)
#=> 3887
array.inject(:/)
#=> 0

谷歌搜索这个问题,我发现了一篇不错的关于注入的文章,但没有提到我尝试过的......
任何人都可以向我解释或提供一些有关我刚刚使用的这些注入命令的信息吗?

Googling on the issue i found a nice article on inject, but no mentioning there about what i've tried....
Can anyone explain to me or give some info about these inject commands that I've just used?

推荐答案

来自 Enumerable#inject:

... 如果你指定一个符号,那么集合中的每个元素都会被传递给 memo 的命名方法.无论哪种情况,结果都会成为 memo 的新值.在迭代结束时,memo 的最终值是该方法的返回值.

... 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.

如果没有明确指定memo的初始值,那么使用集合的第一个元素作为memo的初始值.

If you do not explicitly specify an initial value for memo, then uses the first element of collection is used as the initial value of memo.

因此,如果您指定一个符号,它会将其视为方法名称并在可枚举的每个元素上调用此方法,替换如上所述的备忘录.现在,数学运算符 (+-*/) 只是方法,没有别的.这些行产生相同的结果:

So, if you specify a symbol, it treats it as a method name and invokes this method on every element of the enumerable, replacing memo as stated above. Now, the math operators (+-*/) are just methods, nothing else. These lines produce identical result:

13 + 23 # => 36
13.+(23) # => 36
13.send(:+, 23) # => 36

当您将符号传递给 injectreduce 时,它使用第三种形式将该运算符动态应用于元素:

When you pass a symbol to inject or reduce it uses the third form to dynamically apply that operator to elements:

[1,2,3].inject(:+) # => 6

这个简写也可以用于操作符以外的方法:

This shorthand can be used with methods other than operators as well:

[{"a"=>1}, {"b"=>2}].inject(:merge) # => {"a"=>1, "b"=>2} 

这篇关于是否有任何额外的注入速记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆