How to Call Proc in Ruby: Syntax and Examples
In Ruby, you call a
Proc object using the .call method or the shorthand .() syntax. For example, if you have my_proc = Proc.new { puts 'Hello' }, you can call it with my_proc.call or my_proc.().Syntax
To call a Proc in Ruby, use either the .call method or the shorthand .() syntax.
proc_object.call(arguments): Calls the proc with optional arguments.proc_object.(arguments): A shorter way to call the proc.
The proc executes the block of code it holds, optionally using any arguments passed.
ruby
my_proc = Proc.new { |name| puts "Hello, #{name}!" } my_proc.call("Alice") my_proc.("Bob")
Output
Hello, Alice!
Hello, Bob!
Example
This example shows how to create a proc that takes a name and prints a greeting. It demonstrates calling the proc using both .call and .() methods.
ruby
greet = Proc.new { |name| puts "Hi, #{name}!" } greet.call("Emma") greet.("Liam")
Output
Hi, Emma!
Hi, Liam!
Common Pitfalls
Common mistakes when calling procs include:
- Forgetting to use
.callor.()to execute the proc, which means the proc won't run. - Passing the wrong number of arguments, which can cause errors or unexpected behavior.
- Confusing
Procwithlambda, which handle arguments differently.
ruby
wrong_proc = Proc.new { |x, y| puts x + y } # Wrong: just referencing the proc, no call wrong_proc # Right: calling the proc with arguments wrong_proc.call(2, 3)
Output
5
Quick Reference
| Method | Description | Example |
|---|---|---|
| .call | Calls the proc with arguments | proc.call(1, 2) |
| .() | Shorthand to call the proc | proc.(1, 2) |
| Proc.new | Creates a new proc | Proc.new { |x| x * 2 } |
Key Takeaways
Use .call or .() to execute a proc in Ruby.
Pass the correct number of arguments when calling a proc.
Proc.new creates a proc that can be called later.
Forgetting to call the proc means the code inside won't run.
Procs and lambdas differ in argument handling; know which you use.