Ruby 中的 `&:capitalize` 到底是什么? [英] What exactly is `&:capitalize` in Ruby?
问题描述
我刚刚阅读了这个答案使用 Ruby 将大写字符串转换为标题大小写.
I just read this answer Converting upper-case string into title-case using Ruby.
有下面这行代码
"abc".split(/(\W)/).map(&:capitalize).join
&:capitalize
究竟是什么?在我自己将它放入 irb 之前,我会告诉你,它不是有效的 ruby 语法.它必须是某种 Proc
对象,因为 Array#map
通常需要一个块.但事实并非如此.如果我单独把它放到 irb 中,我会得到 语法错误,意外的 tAMPER
.
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
.
推荐答案
foo(&a_proc_object)
将 a_proc_object
变成一个块并用那个块调用 foo.
foo(&a_proc_object)
turns a_proc_object
into a block and calls foo with that block.
foo(¬_a_proc_object)
在 not_a_proc_object
上调用 to_proc
,然后将 to_proc
返回的 proc 对象转化为进入一个块并用该块调用 foo.
foo(¬_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.
在 ruby 1.8.7+ 和主动支持中,Symbol#to_proc
被定义为返回一个过程,该过程调用过程的参数上的符号命名的方法.
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.
这篇关于Ruby 中的 `&:capitalize` 到底是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!