When passing a Ruby block to a method as an argument, you can use the unary ampersand operator (&
) to convert the block to a Proc
object, for example, like so:
def method_with_block(&block)
puts block.class #=> "Proc"
block.call #=> "Hello World!"
end
# calling the method with a block
method_with_block { puts "Hello World!" }
Apart from using the &
operator in the method parameter list, you can also use various methods that are used for creating a Proc
(such as Proc.new
, Kernel#lambda
, etc.), to explicitly create a Proc
object from a block:
# using `Proc.new` to create `Proc` from block
my_proc = Proc.new { puts "Hello World!" }
my_proc.call #=> "Hello World!"
puts my_proc.class #=> "Proc"
# using `Kernel#lambda` method to create `Proc` from block
my_proc = lambda { puts "Hello World!" }
my_proc.call #=> "Hello World!"
puts my_proc.class #=> "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.