可能重复:
map(&:name)在Ruby中意味着什么?
我遇到了一个代码片段,其中包含以下内容
a.each_slice(2).map(&:reverse)
Run Code Online (Sandbox Code Playgroud)
我不知道&:运营商的功能.这是如何运作的?
Gar*_*eth 81
&:Ruby中没有运算符.您所看到的是&运营商应用于:symbol.
在方法参数列表中,&运算符获取其操作数,Proc如果它尚未(通过调用to_proc它)将其转换为对象,并将其传递给方法,就像使用了块一样.
my_proc = Proc.new { puts "foo" }
my_method_call(&my_proc) # is identical to:
my_method_call { puts "foo" }
Run Code Online (Sandbox Code Playgroud)
所以问题现在变成了"做了Symbol#to_proc什么?",这在Rails文档中很容易看到:
将符号转换为简单的proc,这对于枚举尤其有用.例子:
# 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)
Run Code Online (Sandbox Code Playgroud)
KL-*_*L-7 24
通过&在符号前面创建一个lambda函数,该函数将在传递给此函数的对象上调用带有该符号名称的方法.考虑到这一点:
ar.map(&:reverse)
Run Code Online (Sandbox Code Playgroud)
大致相当于:
ar.map { |element| element.reverse }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34776 次 |
| 最近记录: |