How to Pass Block to Method in Ruby: Simple Guide
In Ruby, you can pass a block to a method by defining the method normally and then calling it with a block using
yield inside the method. Alternatively, you can capture the block as a parameter using &block and call it with block.call.Syntax
To pass a block to a method, you write the method normally and use yield to execute the block inside the method. You can also accept the block as a parameter using &block and call it with block.call.
yield: Runs the block passed to the method.&block: Captures the block as a Proc object.block.call: Executes the captured block.
ruby
def greet puts "Hello" yield if block_given? puts "Goodbye" end
Example
This example shows a method greet that takes a block and runs it between two print statements. It demonstrates both yield and &block usage.
ruby
def greet puts "Hello" yield if block_given? puts "Goodbye" end greet do puts "Nice to meet you!" end # Using &block def greet_with_block(&block) puts "Hello" block.call if block puts "Goodbye" end greet_with_block do puts "Nice to meet you again!" end
Output
Hello
Nice to meet you!
Goodbye
Hello
Nice to meet you again!
Goodbye
Common Pitfalls
Common mistakes include forgetting to check if a block is given before calling yield, which causes an error if no block is passed. Also, confusing yield and &block usage can lead to unexpected behavior.
Always use block_given? before yield or check if block is not nil before calling block.call.
ruby
def wrong_method yield end # Calling without block causes error: # wrong_method # Correct way: def safe_method yield if block_given? end safe_method do puts "Block runs safely" end
Output
Block runs safely
Quick Reference
| Concept | Description | Example |
|---|---|---|
| Passing block with yield | Runs the block inside method | yield if block_given? |
| Capturing block as parameter | Receives block as Proc object | def method(&block) |
| Calling captured block | Executes the block object | block.call if block |
| Check block presence | Avoid errors if no block | block_given? or block != nil |
Key Takeaways
Use
yield inside a method to run a passed block.Use
&block to capture the block as a parameter and call it with block.call.Always check if a block is given with
block_given? before calling yield.For
&block, check if the block is not nil before calling block.call.Passing blocks makes methods flexible and allows custom code execution inside them.