Ruby 试图掌握一种新的符号.(inject(:) vs select(&:even?); 为什么有 &?) [英] Ruby trying to grasp a new notation. (inject(: ) vs select(&:even?); why one has &?)
问题描述
所以,我刚刚了解到,不要写这样的东西:
So, I've just learned that instead of writing things like:
[1,2,3,4,5].inject {|x,y| x + y} => 15
我会写
[1,2,3,4,5].inject(:+) => 15
我也学会了,而不是写作
I also learned that instead of writing
[1,2,3,4,5].select {|x| x.even?} => [2,4]
我会写
[1,2,3,4,5].select(&:even?) => [2,4]
我的问题是为什么一个 (select) 使用 &
而另一个 (inject) 没有.我确定 :
是因为 even?
和 +
被视为符号,但我很想澄清为什么 &
用于其中一个以及为什么使用 :
.
My question is why one (select) uses the &
and the other one (inject) doesn't. I'm sure that the :
are because even?
and +
are treated at symbols, but I'd love clarification behind why the &
is used in one and why the :
are used.
此外,我知道我不仅可以在 inject
和 select
上使用这些符号.
Also, I'm aware that I could do these notations on more than just inject
and select
.
非常感谢!
推荐答案
&
运算符在这种情况下将符号转换为过程.所以代码在幕后做到了这一点:
&
operator in this case converts a symbol to a proc. So the code does this under the hood:
[1,2,3,4,5].select {|elem| elem.send :even? } # => [2, 4]
inject
方法的实现认识到对这些快捷方法规范的需求,并为符号作为参数传递时添加了特殊处理.所以,在这种情况下,它基本上做 &
运算符所做的.
Implementation of inject
method recognizes the need for these shortcut method specification and adds a special handling for when symbol is passes as a parameter. So, in this case, it basically does what &
operator does.
为什么一个(选择)使用 &而另一个(注入)没有
why one (select) uses the & and the other one (inject) doesn't
因为没有人以这种方式实现select
.Ruby 是开源的,他们甚至可以接受你的补丁.去解决这个问题:)
Because nobody implemented select
this way. Ruby is open-source, they may even accept your patch. Go and fix this :)
PS:但如果由我决定,我会改为删除注入的特殊处理.使用 Symbol#to_proc
(这就是 &
运算符使用的)感觉有点多余和混乱.
P.S.: But if it were up to me, I would instead remove inject's special handling. It feels a little bit redundant and confusing in presence of Symbol#to_proc
(that's what &
operator uses).
这篇关于Ruby 试图掌握一种新的符号.(inject(:) vs select(&:even?); 为什么有 &?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!