Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

syntax - What exactly is `&:capitalize` in Ruby?

I just read this answer Converting upper-case string into title-case using Ruby.

There is the following line of code

"abc".split(/(W)/).map(&:capitalize).join

What exactly is &:capitalize? Before I had put this into irb myself, I would have told you, it's not valid ruby syntax. It must be some kind of Proc object, because Array#map normaly takes a block. But it isn't. If I put it into irb alone, I get syntax error, unexpected tAMPER.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

foo(&a_proc_object) turns a_proc_object into a block and calls foo with that block.

foo(&not_a_proc_object) calls to_proc on not_a_proc_object and then turns the proc object returned by to_proc into a block and calls foo with that block.

In ruby 1.8.7+ and active support Symbol#to_proc is defined to return a proc which calls the method named by the symbol on the argument to the proc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...