Ruby&冒号冒号快捷方式

本文翻译自:Ruby ampersand colon shortcut [duplicate]

Possible Duplicate: 可能重复:
What does map(&:name) mean in Ruby? map(&:name)在Ruby中是什么意思?

In Ruby, I know that if I do: 在Ruby中,我知道如果这样做:

some_objects.each(&:foo)

It's the same as 和...一样

some_objects.each { |obj| obj.foo }

That is, &:foo creates the block { |obj| obj.foo } 也就是说, &:foo创建块{ |obj| obj.foo } { |obj| obj.foo } , turns it into a Proc, and passes it to each. { |obj| obj.foo } ,将其转换为Proc,并将其传递给每个对象。 Why does this work? 为什么这样做? Is it just a Ruby special case, or is there reason why this works as it does? 它仅仅是Ruby的特例,还是有理由使它如此工作?


#1楼

参考:https://stackoom.com/question/8E9W/Ruby-冒号冒号快捷方式


#2楼

Your question is wrong, so to speak. 您的问题是错误的,可以这么说。 What's happening here isn't "ampersand and colon", it's "ampersand and object". 这里发生的不是“与号和冒号”,而是“与号和对象”。 The colon in this case is for the symbol. 在这种情况下,冒号用于符号。 So, there's & and there's :foo . 因此,有&并且有:foo

The & calls to_proc on the object, and passes it as a block to the method. &调用对象上的to_proc ,并将其作为块传递给方法。 In Rails, to_proc is implemented on Symbol , so that these two calls are equivalent: 在Rails中, to_proc是在Symbol上实现的,因此这两个调用是等效的:

something {|i| i.foo }
something(&:foo)

Also, to_proc on Symbol is implemented in Ruby 1.8.7 and 1.9, so it is in fact a "ruby thing". 另外,在Symbol 1.8.2和1.9中实现了Symbol上的to_proc ,因此它实际上是“红宝石”。

So, to sum up: & calls to_proc on the object and passes it as a block to the method, and Ruby implements to_proc on Symbol . 因此,总结一下: &调用对象上的to_proc并将其作为块传递给方法,并且Ruby在Symbol上实现to_proc


#3楼

There's nothing special about the combination of the ampersand and the symbol. “&”号和符号的组合没有什么特别的。 Here's an example that (ab)uses the regex: 这是(ab)使用正则表达式的示例:

class Regexp
  def to_proc
    ->(str) { self =~ str ; $1 }
  end
end
%w(station nation information).map &/(.*)ion/

=> ["stat", "nat", "informat"]

Or integers. 或整数。

class Integer
  def to_proc
    ->(arr) { arr[self] }
  end
end

arr = [[*3..7],[*14..27],[*?a..?z]]
arr.map &4
=> [7, 18, "e"]

Who needs arr.map(&:fifth) when you have arr.map &4 ? 当您拥有arr.map &4时,谁需要arr.map(&:fifth)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值