问题描述
可能的重复:
Ruby/Ruby on Rails &符号冒号快捷方式
map(&:name) 在 Ruby 中是什么意思?
我正在阅读 Stackoverflow 并偶然发现以下代码
I was reading Stackoverflow and stumbled upon the following code
array.map(&:to_i)
好的,很容易看出这段代码做了什么,但我想更多地了解我以前从未见过的 &:
构造.
Ok, it's easy to see what this code does but I'd like to know more about &:
construct which I have never seen before.
不幸的是,我能想到的只是lambda",但事实并非如此.Google 告诉我 Ruby 中的 lambda 语法是 ->->(x,y){ x * y }
Unfortunately all I can think of is "lambda" which it is not. Google tells me that lambda syntax in Ruby is ->->(x,y){ x * y }
那么有谁知道那个神秘的 &:
是什么以及它除了调用单个方法之外还能做什么?
So anyone knows what that mysterious &:
is and what it can do except calling a single method?
推荐答案
这里有一些动人的部分,但正在发生的事情的名称是 Symbol#to_proc
转换.这是 Ruby 1.9 及更高版本的一部分,如果您使用更高版本的 Rails,也可以使用.
There's a few moving pieces here, but the name for what's going on is the Symbol#to_proc
conversion. This is part of Ruby 1.9 and up, and is also available if you use later-ish versions of Rails.
首先,在 Ruby 中,:foo
的意思是符号 foo
",所以它实际上是您正在查看的两个独立的运算符,而不是一个大的 &:
运算符.
First, in Ruby, :foo
means "the symbol foo
", so it's actually two separate operators you're looking at, not one big &:
operator.
当您说 foo.map(&bar)
时,您是在告诉 Ruby,向 foo
对象发送消息以调用 map
方法,我已经定义了一个名为 bar
的块".如果 bar
还不是 Proc
对象,Ruby 会尝试将其变成一个.
When you say foo.map(&bar)
, you're telling Ruby, "send a message to the foo
object to invoke the map
method, with a block I already defined called bar
". If bar
is not already a Proc
object, Ruby will try to make it one.
在这里,我们实际上并没有传递一个块,而是一个名为 bar
的符号.因为我们在 Symbol
上有一个隐式的 to_proc
转换可用,Ruby 看到并使用它.原来这个转换看起来是这样的:
Here, we don't actually pass a block, but instead a symbol called bar
. Because we have an implicit to_proc
conversion available on Symbol
, Ruby sees that and uses it. It turns out that this conversion looks like this:
def to_proc
proc { |obj, *args| obj.send(self, *args) }
end
这会生成一个 proc
,它调用与符号同名的方法.将所有内容放在一起,使用您的原始示例:
This makes a proc
which invokes the method with the same name as the symbol. Putting it all together, using your original example:
array.map(&:to_i)
这会在数组上调用 .map
,并且对于数组中的每个元素,返回对该元素调用 to_i
的结果.
This invokes .map
on array, and for each element in the array, returns the result of calling to_i
on that element.
这篇关于Ruby 中的 &: 运算符叫什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!