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?
&Proc.new
do in a method?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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With