Ruby 和号冒号快捷方式 [英] Ruby ampersand colon shortcut
问题描述
可能的重复:
map(&:name) 在 Ruby 中是什么意思?
在 Ruby 中,我知道如果我这样做:
In Ruby, I know that if I do:
some_objects.each(&:foo)
与
some_objects.each { |obj| obj.foo }
也就是说,&:foo
创建块 { |obj|obj.foo }
,将其转换为 Proc,并将其传递给每个.为什么这样做?这只是 Ruby 的一个特例,还是有理由这样工作?
That is, &:foo
creates the block { |obj| obj.foo }
, turns it into a Proc, and passes it to each. Why does this work? Is it just a Ruby special case, or is there reason why this works as it does?
推荐答案
可以这么说,您的问题是错误的.这里发生的不是&符号和冒号",而是&符号和对象".在这种情况下,冒号用于符号.所以,有 &
和 :foo
.
Your question is wrong, so to speak. What's happening here isn't "ampersand and colon", it's "ampersand and object". The colon in this case is for the symbol. So, there's &
and there's :foo
.
&
调用对象上的 to_proc
,并将其作为块传递给方法.在Ruby中,to_proc
是在Symbol
上实现的,所以这两个调用是等价的:
The &
calls to_proc
on the object, and passes it as a block to the method. In Ruby, to_proc
is implemented on Symbol
, so that these two calls are equivalent:
something {|i| i.foo }
something(&:foo)
所以,总结一下:&
在对象上调用 to_proc
并将其作为块传递给方法,Ruby 实现了 to_proc
在 Symbol
上.
So, to sum up: &
calls to_proc
on the object and passes it as a block to the method, and Ruby implements to_proc
on Symbol
.
这篇关于Ruby 和号冒号快捷方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!