How to Create a Proc in Ruby?

Procs come in two variations; lambda and non-lambda (i.e. regular procs), and can be created using any of the following:

  1. Proc.new method;
  2. proc method;
  3. Kernel#lambda method;
  4. -> (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.