ruby 中“&:”运算符的功能是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9429819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:48:54  来源:igfitidea点击:

what is the functionality of "&: " operator in ruby?

ruby

提问by Rahul

Possible Duplicate:
What does map(&:name) mean in Ruby?

可能的重复:
map(&:name) 在 Ruby 中是什么意思?

I came across a code snippet which had the following

我遇到了一个代码片段,其中包含以下内容

a.each_slice(2).map(&:reverse)

I do not know the functionality of &:operator. How does that work?

我不知道&:运算符的功能。这是如何运作的?

回答by Gareth

There isn't a &:operator in Ruby. What you are seeing is the &operator applied to a :symbol.

&:Ruby 中没有运算符。您看到的是&应用于 a的运算符:symbol

In a method argument list, the &operator takes its operand, converts it to a Procobject if it isn't already (by calling to_procon it) and passes it to the method as if a block had been used.

在方法参数列表中,&操作符获取它的操作数,Proc如果它还没有(通过调用to_proc它)将其转换为对象,并将其传递给方法,就像使用了块一样。

my_proc = Proc.new { puts "foo" }

my_method_call(&my_proc) # is identical to:
my_method_call { puts "foo" }

So the question now becomes "What does Symbol#to_procdo?", and that's easy to see in the Rails documentation:

所以问题现在变成了“做Symbol#to_proc什么?”,这在Rails 文档中很容易看到:

Turns the symbol into a simple proc, which is especially useful for enumerations. Examples:

将符号变成一个简单的过程,这对枚举特别有用。例子:

# The same as people.collect { |p| p.name }
people.collect(&:name)

# The same as people.select { |p| p.manager? }.collect { |p| p.salary }
people.select(&:manager?).collect(&:salary)

回答by KL-7

By prepending &to a symbol you are creating a lambda function that will call method with a name of that symbol on the object you pass into this function. Taking that into account:

通过添加&一个符号,您将创建一个 lambda 函数,该函数将在传递给此函数的对象上调用具有该符号名称的方法。考虑到这一点:

ar.map(&:reverse)

is roughly equivalent to:

大致相当于:

ar.map { |element| element.reverse }