Quick Answer
Blocks are anonymous functions that can be passed to methods.
Understanding the Issue
Ruby blocks are chunks of code between do/end or curly braces {}. They can be passed to methods like each, map, etc. and executed with yield.
The Problem
This code demonstrates the issue:
Ruby
Error
# Problem: Inefficient iteration
[1,2,3].each do |n|
puts n * 2
end
The Solution
Here's the corrected code:
Ruby
Fixed
# Solution 1: Using blocks
[1,2,3].map { |n| n * 2 }
# Solution 2: Custom block method
def triple
yield * 3
end
triple { 5 } # => 15
Key Takeaways
Blocks enable powerful functional programming patterns.