In Ruby, when passing a Proc
object to a method as an argument, you can use the unary ampersand operator (&
) to convert it to a block, for example, like so:
# create a method that accepts a block
def my_method(&block)
if block_given?
# call the block using `yield`
yield(10)
else
"not a block"
end
end
my_proc = proc { | x | puts x * 2 }
# convert the `Proc` to a block and pass it to the method
puts my_method(&my_proc) #=> 20
This can be useful for passing a Proc
(or lambda) to a method that expects a block argument. In the example above, Kernel#block_given?
returns true
and yield
executes the block in the current context as expected.
If you modify the code above and remove the &
operator, you will see that the method argument is no longer treated as a block:
def my_method(block)
if block_given?
yield(10)
else
"not a block"
end
end
my_proc = proc { | x | puts x * 2 }
puts my_method(my_proc) #=> "not a block"
Please note that when a Proc
object is converted to a block using the &
operator, it can still be invoked using the Proc#call
method as it retains its underlying functionality. This also means that when you call the class
method on the object inside the method, it will return "Proc
".
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.