How to Create a Proc in Ruby: Syntax and Examples
In Ruby, you create a
Proc using Proc.new or the proc method followed by a block of code. This creates a reusable block of code that you can call later with call.Syntax
A Proc is created by calling Proc.new or proc with a block. The block contains the code you want to reuse. You can then run the proc using call.
- Proc.new { |args| ... }: Creates a new Proc object.
- proc { |args| ... }: Another way to create a Proc.
- call(args): Runs the Proc with optional arguments.
ruby
my_proc = Proc.new { |name| puts "Hello, #{name}!" } my_proc.call("Alice")
Output
Hello, Alice!
Example
This example shows how to create a Proc that takes a number, doubles it, and prints the result. Then it calls the Proc with different numbers.
ruby
doubler = proc { |x| puts x * 2 }
doubler.call(5)
doubler.call(10)Output
10
20
Common Pitfalls
One common mistake is forgetting to use call to run the Proc. Another is confusing Procs with lambdas, which handle arguments and returns differently.
Also, using Proc.new without a block raises an error.
ruby
wrong_proc = Proc.new # Raises error: no block given (LocalJumpError) correct_proc = Proc.new { puts "This works!" } correct_proc.call
Output
This works!
Quick Reference
| Action | Syntax | Description |
|---|---|---|
| Create Proc | Proc.new { |args| ... } | Creates a new Proc object with a block |
| Create Proc | proc { |args| ... } | Alternative way to create a Proc |
| Call Proc | proc_object.call(args) | Runs the Proc with given arguments |
| Check Proc | proc_object.is_a?(Proc) | Returns true if object is a Proc |
Key Takeaways
Create a Proc in Ruby using Proc.new or proc with a block.
Run a Proc by calling its call method with arguments.
Always provide a block when creating a Proc to avoid errors.
Procs are reusable blocks of code that can take parameters.
Remember Procs differ from lambdas in argument handling and return behavior.