0
0
RubyConceptBeginner · 3 min read

What is Proc in Ruby: Explanation and Examples

In Ruby, a Proc is an object that holds a block of code which can be stored in a variable and executed later. It allows you to treat code like data, passing it around and calling it whenever needed.
⚙️

How It Works

A Proc in Ruby is like a little package of code you can carry around. Imagine you write a recipe on a card and keep it in your pocket. Whenever you want to cook that recipe, you just take out the card and follow the steps. Similarly, a Proc stores code that you can run anytime by calling it.

Under the hood, a Proc remembers the environment where it was created, so it can use variables from that place even when called somewhere else. This makes it very flexible for reusing code and passing behavior as an object.

💻

Example

This example shows how to create a Proc, store it in a variable, and call it to run the code inside.

ruby
say_hello = Proc.new { |name| puts "Hello, #{name}!" }
say_hello.call("Alice")
Output
Hello, Alice!
🎯

When to Use

Use a Proc when you want to save a piece of code to run later or pass it to other methods. For example, you can use it to customize behavior in loops, callbacks, or event handlers without repeating code.

Real-world uses include filtering lists, defining reusable actions, or delaying execution until a certain condition happens.

Key Points

  • A Proc is an object that holds code you can run later.
  • It can take parameters and remember the context where it was created.
  • You call a Proc using call or [].
  • It helps make your code more flexible and reusable.

Key Takeaways

A Proc is a reusable block of code stored as an object in Ruby.
You can pass Procs around and call them whenever needed.
Procs remember the environment where they were created.
Use Procs to write flexible and DRY (Don't Repeat Yourself) code.