Ruby Blocks, Procs, and Lambdas Explained
Understanding the differences between blocks, procs, and lambdas is key to writing idiomatic Ruby.
Key Insights
- Blocks are the most common — every Ruby method can accept one implicitly
- Lambdas check argument count and return to their caller; procs don’t
- Use &method(:name) to convert methods to proc objects for clean functional style
Blocks
[1, 2, 3].each do |n|
puts n * 2
end
# Single-line form
[1, 2, 3].map { |n| n * 2 }
Lambda vs Proc
# Lambda checks arity
multiply = ->(a, b) { a * b }
multiply.call(2, 3) # => 6
multiply.call(2) # ArgumentError!
# Proc is lenient
flexible = Proc.new { |a, b| (a || 0) * (b || 1) }
flexible.call(2) # => 2 (b is nil, becomes 1)
Method References
words = ["hello", "world"]
words.map(&method(:puts)) # passes each word to puts
words.select(&:frozen?) # symbol-to-proc shorthand