How to Pass Proc to Method in Ruby: Simple Guide
In Ruby, you can pass a
Proc object to a method by using the & symbol before the proc parameter in the method definition. When calling the method, pass the proc as an argument with & to convert it into a block.Syntax
To pass a proc to a method, define the method with a parameter prefixed by &. This tells Ruby to convert the proc into a block inside the method. When calling the method, pass the proc with & to convert it back into a block.
def method_name(&block): method accepts a proc as a blockmethod_name(&proc_variable): pass proc as block
ruby
def example_method(&block) block.call end my_proc = Proc.new { puts "Hello from proc!" } example_method(&my_proc)
Output
Hello from proc!
Example
This example shows how to define a method that takes a proc and calls it. The proc is created separately and passed to the method using &. The method then runs the proc's code.
ruby
def greet(&block) puts "Before proc call" block.call("Ruby") puts "After proc call" end say_hello = Proc.new { |name| puts "Hello, #{name}!" } greet(&say_hello)
Output
Before proc call
Hello, Ruby!
After proc call
Common Pitfalls
Common mistakes include forgetting the & when passing the proc to the method or when defining the method parameter. Without &, Ruby treats the proc as a normal argument, not a block, causing errors when calling block.call.
Also, passing a block directly without converting it to a proc when needed can cause confusion.
ruby
def wrong_method(block) block.call end my_proc = Proc.new { puts "Hi!" } # This will cause an error because block is not a proc but a normal argument # wrong_method(my_proc) #=> NoMethodError # Correct way: def right_method(&block) block.call end right_method(&my_proc)
Quick Reference
| Action | Syntax | Description |
|---|---|---|
| Define method to accept proc | def method_name(&block) | Method receives proc as block parameter |
| Pass proc to method | method_name(&proc_variable) | Convert proc to block when calling |
| Call proc inside method | block.call | Execute the proc's code |
| Create proc | my_proc = Proc.new { ... } | Define a proc object |
Key Takeaways
Use & before a parameter in method definition to accept a proc as a block.
Pass a proc to a method by prefixing it with & to convert it into a block.
Inside the method, call the proc using block.call to run its code.
Forgetting & when passing or receiving procs causes errors.
Procs allow flexible code blocks to be passed around and reused.