Ruby 中的 :+ 和 &:+ 是什么? [英] What are :+ and &:+ in Ruby?
问题描述
我已经看过好几次了,但我不知道如何使用它们.镐说这些是特殊的快捷方式,但我找不到语法描述.
I've seen these several times but I can't figure out how to use them. The pickaxe says that these are special shortcuts but I wasn't able to find the syntactical description.
我在这种情况下见过它们:
I've seen them in such contexts:
[1,2,3].inject(:+)
例如计算总和.
推荐答案
让我们从一个更简单的例子开始.假设我们有一个想要大写的字符串数组:
Let's start with an easier example. Say we have an array of strings we want to have in caps:
['foo', 'bar', 'blah'].map { |e| e.upcase }
# => ['FOO', 'BAR', 'BLAH']
此外,您还可以创建所谓的 Proc 对象(闭包):
Also, you can create so called Proc objects (closures):
block = proc { |e| e.upcase }
block.call("foo") # => "FOO"
您可以使用 & 将这样的过程传递给方法.语法:
You can pass such a proc to a method with the & syntax:
block = proc { |e| e.upcase }
['foo', 'bar', 'blah'].map(&block)
# => ['FOO', 'BAR', 'BLAH']
这样做是在块上调用 to_proc,然后为每个块调用它:
What this does, is call to_proc on block and then calls that for every block:
some_object = Object.new
def some_object.to_proc
proc { |e| e.upcase }
end
['foo', 'bar', 'blah'].map(&some_object)
# => ['FOO', 'BAR', 'BLAH']
现在,Rails 首先将 to_proc 方法添加到 Symbol 中,该方法后来被添加到 ruby 核心库中:
Now, Rails first added the to_proc method to Symbol, which later has been added to the ruby core library:
:whatever.to_proc # => proc { |e| e.whatever }
因此您可以这样做:
['foo', 'bar', 'blah'].map(&:upcase)
# => ['FOO', 'BAR', 'BLAH']
此外,Symbol#to_proc 更智能,因为它实际上执行以下操作:
Also, Symbol#to_proc is even smarter, as it actually does the following:
:whatever.to_proc # => proc { |obj, *args| obj.send(:whatever, *args) }
这意味着
[1, 2, 3].inject(&:+)
等于
[1, 2, 3].inject { |a, b| a + b }
这篇关于Ruby 中的 :+ 和 &:+ 是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!