How to Check if Block is Given in Ruby: Simple Guide
In Ruby, you can check if a block is given to a method using the
block_given? method. It returns true if a block is passed, otherwise false. Use this inside your method to conditionally execute block code.Syntax
The block_given? method is called inside a method to check if a block was passed when the method was called. It returns true if a block exists, otherwise false.
Example syntax:
def method_name- defines a methodif block_given?- checks if block is passedyield- runs the blockend- closes the if and method
ruby
def example_method if block_given? yield else puts "No block given" end end
Example
This example shows a method that prints a message if no block is given, or runs the block if it is given.
ruby
def greet if block_given? yield else puts "Hello, no block provided!" end end greet greet { puts "Hello from the block!" }
Output
Hello, no block provided!
Hello from the block!
Common Pitfalls
A common mistake is to try to call yield without checking if a block is given, which causes an error if no block is passed.
Always use block_given? before yield to avoid LocalJumpError.
ruby
def wrong_method yield end # Calling without block causes error: # wrong_method #=> LocalJumpError # Correct way: def safe_method if block_given? yield else puts "No block to yield" end end
Quick Reference
| Method | Description |
|---|---|
| block_given? | Returns true if a block is passed to the method |
| yield | Executes the block passed to the method |
| if block_given? ... yield | Safe way to run block only if given |
Key Takeaways
Use
block_given? inside a method to check if a block was passed.Always check
block_given? before calling yield to avoid errors.If no block is given, you can provide alternative code or messages.
Blocks allow flexible code execution passed to methods.
Remember
block_given? returns a boolean, useful for conditional logic.