ruby-on-rails – 表达式和Proc.new在方法中做了什么?

我在rails源中找到了& Proc.new的用法

# rails/railties/lib/rails/engine.rb
def routes
  @routes ||= Actiondispatch::Routing::RouteSet.new
  @routes.append(&Proc.new) if block_given?
  @routes
end

我不明白表达式和Proc.new是如何工作的.

我写了类似的代码,但失败了:

def method_name
  &Proc.new if block_given?
end
proc = method_name{ puts 'Hello World!' }
proc.call

我收到了语法错误

Syntax error,unexpected &
    &Proc.new if block_given?

>表达式和Proc.new在方法中做了什么?

解决方法

&安培;在参数列表中有一个特殊的含义 – 当用作Proc对象的前缀时,它将它作为块传递给被调用方法.在方法体内,它只是一个二元运算符.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...