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.
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.
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.
greet = Proc.new { puts "Hello!" } greet.call
square = proc { |x| x * x } puts square.call(4)
say_name = Proc.new { |name| puts "Your name is #{name}" } say_name.call("Alice")
This program creates a Proc to double a number, calls it with 5, and prints the result.
double = Proc.new { |n| n * 2 } result = double.call(5) puts "Double of 5 is #{result}"
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.
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.
Proc in Ruby do?Proc.new or proc with a block. Only my_proc = Proc.new { |x| x * 2 } uses the correct syntax Proc.new { |x| x * 2 }. Others use invalid methods like new Proc, Proc.create, or Proc.call.my_proc = proc { |x| x + 3 }
puts my_proc.call(4)x + 3. Calling my_proc.call(4) computes 4 + 3 = 7.my_proc = Proc.new { |x| x * 2 }
puts my_proc.callx to multiply by 2. The call is made without any argument, which causes an error because x is missing.def create_proc
Proc.new { |x| x.nil? ? 'No value' : x * 10 }
end
my_proc = create_proc
puts my_proc.call(nil)
puts my_proc.call(5)x is nil; if yes, returns 'No value', else returns x * 10. Calling with nil returns 'No value'. Calling with 5 returns 5 * 10 = 50.Pass the test and this pattern moves unknown