What is block_given in Ruby: Explanation and Examples
block_given? is a Ruby method that checks if a block has been passed to a method. It returns true if a block is provided, otherwise false. This helps methods decide whether to execute the block or not.How It Works
In Ruby, methods can optionally receive a block of code, like a little package of instructions. The block_given? method acts like a sensor inside a method to detect if this package was handed over. Think of it like asking, "Did you bring me a note to read?" If yes, block_given? returns true; if no, it returns false.
This is useful because sometimes a method can behave differently depending on whether it has a block to run. Without a block, the method might do a default action, but with a block, it can yield control to that block to customize behavior.
Example
This example shows a method that checks if a block is given and runs it if present. Otherwise, it prints a default message.
def greet if block_given? yield else puts "Hello, no block was given!" end end greet { puts "Hello from the block!" } greet
When to Use
Use block_given? when you want your method to optionally accept a block and behave differently if the block is present. This is common in methods that can either perform a default action or allow the caller to customize the action with a block.
For example, iterators like each use blocks to run code on each item. You might write your own methods that yield to blocks only if they exist, making your code flexible and reusable.
Key Points
block_given?returnstrueif a block is passed to the method.- It helps methods decide whether to call
yieldsafely. - Using it avoids errors when no block is provided.
- It makes methods more flexible and customizable.
Key Takeaways
block_given? checks if a block was passed to a method.block_given? to safely call yield only when a block exists.