Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
96 views
in Technique[技术] by (71.8m points)

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(:+)

to calculate sum for example.

question from:https://stackoverflow.com/questions/2697024/what-are-and-in-ruby

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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']

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']

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']

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 }

Therefore you can do this:

['foo', 'bar', 'blah'].map(&:upcase)
# => ['FOO', 'BAR', 'BLAH']

Also, Symbol#to_proc is even smarter, as it actually does the following:

:whatever.to_proc # => proc { |obj, *args| obj.send(:whatever, *args) }

This means that

[1, 2, 3].inject(&:+)

equals

[1, 2, 3].inject { |a, b| a + b }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...