How to Use Block in Ruby: Simple Guide with Examples
block is a chunk of code enclosed in { } or do...end that you can pass to methods to run later. You use blocks by placing them after a method call, and inside the method, you can execute the block with yield or by calling a block parameter.Syntax
A block in Ruby is written either with curly braces { } for single-line blocks or with do...end for multi-line blocks. You attach a block to a method call by placing it right after the method's parentheses or arguments. Inside the method, you can run the block using yield or by accepting a block parameter with &block and calling block.call.
- Curly braces: Used for short, single-line blocks.
- do...end: Used for longer, multi-line blocks.
- yield: Runs the block passed to the method.
- &block: Captures the block as a Proc object to call explicitly.
def greet yield end greet { puts "Hello from the block!" }
Example
This example shows a method repeat that takes a number and a block. It runs the block the given number of times using yield. The block prints a message each time it runs.
def repeat(times)
times.times do |i|
yield(i + 1)
end
end
repeat(3) do |count|
puts "This is repetition number #{count}"
endCommon Pitfalls
Common mistakes when using blocks include forgetting to pass a block when the method expects one, or calling yield without checking if a block was given, which causes an error. Also, confusing when to use { } versus do...end can affect readability but not functionality.
Always check if a block is given with block_given? before calling yield to avoid errors.
def safe_greet if block_given? yield else puts "No block given!" end end safe_greet { puts "Hello!" } safe_greet
Quick Reference
| Concept | Description | Example |
|---|---|---|
| Block syntax | Use { } for single-line, do...end for multi-line | method { puts 'Hi' } or method do puts 'Hi' end |
| Calling block | Use yield inside method to run block | yield |
| Block parameter | Capture block as &block to call explicitly | def m(&block); block.call; end |
| Check block | Use block_given? to avoid errors | if block_given?; yield; end |