Ruby Proc 语法 [英] Ruby Proc Syntax

查看:53
本文介绍了Ruby Proc 语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我昨天在这里提出的一个问题的答案是以下一段 Ruby 代码:

An answer to a question I posed yesterday on here was the following piece of Ruby code:

def overlap?(r1,r2)
  r1.include?(r2.begin) || r2.include?(r1.begin)
end

def any_overlap?(ranges)
  ranges.sort_by(&:begin).each_cons(2).any? do |r1,r2|
  overlap?(r1, r2)
  end
end

我得到了 each_cons,但是奇怪的 &:begin 符号是什么?把我从语法地狱中拯救出来!

I get each_cons, but what's the strange &:begin notation? Save me from syntax hell!

谢谢!

推荐答案

当您在调用的最后一个参数前加上 & 时,您就明确表示您发送的是块而不是 正常参数.好的,在 method(&:something) 中,:something 是一个符号,而不是一个 proc,所以 Ruby 会自动调用方法 to_proc 得到一个真正的块.而 Rails 的人(现在还有 vanilla Ruby)巧妙地将其定义为:

When you prefix the last argument of a call with & you are making clear that you are sending a block and not a normal argument. Ok, in method(&:something), :something is a symbol, not a proc, so Ruby automatically calls the method to_proc to get a real block. And Rails guys (and now also vanilla Ruby) cleverly defined it as:

class Symbol
  def to_proc
    proc { |obj, *args| obj.send(self, *args) }
  end
end

这就是为什么你可以这样做:

That's why you can do:

>> [1, 2, 3].map(&:to_s) # instead of [1, 2, 3].map { |n| n.to_s }
=> ["1", "2", "3"]

[edit] 注意:当您意识到这种构造不是语法糖而是 Ruby 提供的通用基础结构时,没有什么能阻止您为其他类实现自己的 to_proc.从未因为 &:method 不允许任何参数而感到受限?

[edit] Note: when you realize that this construction is no syntatic sugar but generic infrastructure that Ruby provides, nothing stops you from implementing your own to_proc for other classes. Never felt limited because &:method allowed no arguments?

class Array
  def to_proc
    proc { |obj, *args| obj.send(*(self + args)) }
  end
end

>> ["1", "F", "FF"].map(&[:to_i, 16])
=> [1, 15, 255]

这篇关于Ruby Proc 语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆