0
0
Rubyprogramming~5 mins

Proc creation and call in Ruby

Choose your learning style9 modes available
Introduction

A Proc lets you save a small piece of code to use later. It helps you run the same code many times without rewriting it.

When you want to reuse a block of code multiple times.
When you want to pass a block of code as an argument to a method.
When you want to store a piece of code in a variable for later use.
When you want to delay running some code until a certain event happens.
Syntax
Ruby
my_proc = Proc.new { |args| code }

# or
my_proc = proc { |args| code }

# To call the proc:
my_proc.call(arguments)

You create a Proc using Proc.new or the shortcut proc.

You run the saved code by calling call on the Proc.

Examples
This creates a Proc that prints "Hello!" and then runs it.
Ruby
greet = Proc.new { puts "Hello!" }
greet.call
This Proc takes a number and returns its square. We call it with 4 and print the result.
Ruby
square = proc { |x| x * x }
puts square.call(4)
This Proc takes a name and prints a message including that name.
Ruby
say_name = Proc.new { |name| puts "Your name is #{name}" }
say_name.call("Alice")
Sample Program

This program creates a Proc to double a number, calls it with 5, and prints the result.

Ruby
double = Proc.new { |n| n * 2 }
result = double.call(5)
puts "Double of 5 is #{result}"
OutputSuccess
Important Notes

If you forget to use call, the Proc won't run.

Procs can take any number of arguments, just like methods.

Using Procs helps keep your code clean and avoids repeating yourself.

Summary

A Proc stores code you can run later.

Create a Proc with Proc.new or proc.

Run the Proc using call with any needed arguments.