Block / yield / block_given?
A block is a chunk of code that can be passed to a method. Use yield to call a block, and block_given? to check whether a block was provided.
Syntax
# Call a method with a block (do...end form).
method_name do |argument|
process
end
# Call a method with a block ({} form).
method_name { |argument| process }
# Call the block inside a method definition.
def method_name
yield # Executes the block.
yield(argument) # Executes the block, passing an argument.
end
# Check whether a block was provided.
def method_name
if block_given?
yield
end
end
Syntax List
| Syntax / Method | Description |
|---|---|
| do...end | Defines a multi-line block. Has lower precedence, so it is commonly used when combining with method arguments. |
| { } | Defines a single-line block. Has higher precedence and is used for inline blocks. |
| yield | Executes the block passed to the method. You can also pass arguments to the block. |
| block_given? | Returns a boolean indicating whether a block was passed to the method. |
Sample Code
# Define a method that calls a block with yield.
def greet
puts "Starting."
yield # Executes the block.
puts "Done."
end
greet do
puts "Hello!"
end
# Pass an argument with yield.
def double(number)
yield(number * 2)
end
double(5) { |n| puts "Result: #{n}" } # Result: 10
# Use block_given? to check whether a block was provided.
def optional_process(value)
if block_given?
yield(value)
else
puts "No block: #{value}"
end
end
optional_process(42) # No block: 42
optional_process(42) { |n| puts "With block: #{n}" } # With block: 42
# Use the return value of yield.
def transform(text)
result = yield(text)
puts "Transformed: #{result}"
end
transform("hello") { |s| s.upcase } # Transformed: HELLO
Overview
Blocks are a core feature of Ruby that let you attach a piece of code to a method after the fact. Iterators such as each and map are also implemented as methods that accept blocks.
Both do...end and { } define blocks, but by convention do...end is used for multi-line blocks and { } for single-line blocks. Calling yield without a block raises a LocalJumpError, so always check with block_given? when a block is optional.
If you find any errors or copyright issues, please contact us.