Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the expression &Proc.new do in a method?

I found usage of &Proc.new in the rails sources:

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

I don't understand how the expression &Proc.new works.

I wrote similar code and it failed:

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

I received a syntax error:

syntax error, unexpected &
    &Proc.new if block_given?
  • What does the expression &Proc.new do in a method?
like image 762
Oleh Tsyba Avatar asked Feb 13 '23 22:02

Oleh Tsyba


1 Answers

First you should know and understand what blocks and Procs are. Basically they are the way ruby provides closures. Here is a good link.

The unary ampersand operator in ruby has 3 uses (all of them related to blocks and Procs):

  • If applied to an argument in a method definition, then the implicit block parameter is stored as a Proc using the argument name.

  • If applied to a Proc in a method call, then the block contained in the Proc is passed as the implicit block parameter. It preserves whether the Proc is a lambda or not. Methods are always lambdas.

  • If applied to other object in a method call, the method #to_proc is called and the resulting Proc is passed as in the second case.

The & Operator in Ruby explains it in detail.

like image 72
dorellang Avatar answered Feb 25 '23 05:02

dorellang