What Is a "Proc" in Ruby?

In Ruby, a "Proc" is a built-in class that is used for representing an anonymous function, or a block of code. It can be created using various methods (such as Proc.new, Kernel#lambda, etc.).

For example:

# `Proc` representing an anonymous function
my_proc = Proc.new { | name | puts "Hello, #{name}!" }

my_proc.call("John") #=> "Hello, John!"
# `Proc` representing a block of code
my_block = proc {
  puts "Inside the block"
  # ...
}

my_block.call #=> "Inside the block"

"Proc" is short for procedure. You can think of it as being similar to a lambda function or a closure in other programming languages. Essentially, a Proc object encapsulates a block of code, which can be stored in a variable, passed as an argument to a method, or returned as a value from a method.


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.