What is Block in Ruby: Simple Explanation and Examples
block is a chunk of code enclosed between do...end or curly braces {...} that can be passed to methods to be executed. Blocks let you write reusable code that runs inside methods, like giving instructions to a helper.How It Works
Think of a block in Ruby as a little recipe you hand to a method. The method can then follow that recipe whenever it wants. This lets you customize what the method does without changing the method itself.
Blocks are not objects but can be called by methods using the yield keyword or by converting them into Proc objects. When a method receives a block, it can run the block's code at any point, passing values in or getting results back.
This is like giving a friend a set of instructions on how to prepare your favorite sandwich. Your friend (the method) can follow those instructions (the block) whenever they make the sandwich.
Example
This example shows a method that takes a block and runs it using yield. The block prints a message.
def greet puts "Hello!" yield puts "Goodbye!" end greet do puts "Nice to meet you." end
When to Use
Use blocks when you want to let methods perform custom actions without rewriting the method. They are great for tasks like iterating over items, handling resources, or defining callbacks.
For example, Ruby's built-in methods like each use blocks to run code on every item in a list. Blocks help keep your code clean and flexible by separating the "what to do" from the "when to do it."
Key Points
- A block is a chunk of code passed to a method.
- Blocks are enclosed in
do...endor curly braces{...}. - Methods use
yieldto run the block. - Blocks let you customize method behavior without changing the method.
- Commonly used for iteration, callbacks, and resource management.