Procs come in two variations; lambda and non-lambda (i.e. regular procs), and can be created using any of the following:
Proc.new
method;proc
method;Kernel#lambda
method;->
(lambda literal syntax / stabby lambda syntax).
For example, the following shows different ways of creating a Proc
object:
# using `Proc.new`
my_proc = Proc.new { puts "Hello World!" }
# using the `proc` method
my_proc = proc { puts "Hello World!" }
# using `lambda` method
my_proc = lambda { puts "Hello World!" }
# using lambda literal syntax (`->`)
my_proc = -> { puts "Hello World!" }
You can invoke any of these procs by calling the Proc#call
method:
# ...
my_proc.call #=> "Hello World!"
puts my_proc.class #=> Proc
It's important to note that lambda and non-lambda procs have some semantic differences that you should be aware of.
A Proc
and block can both be used to represent chunks of code. However, they have some differences between them. That being said, a block can easily be converted to a Proc
, and vice versa.
This post was published (and was last revised ) 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.