Blocks, Procs, Lambdas
Use blocks with yield, Procs, lambdas, and the & operator.
Code
# Block - implicit, passed to a method call
[1, 2, 3].each { |n| puts n }
result = [1, 2, 3].map { |n| n * 2 }
puts result.inspect
# yield to caller's block
def repeat(n)
n.times { yield }
end
repeat(3) { print "hi " }
puts
# Proc - explicit object wrapping a block
square = Proc.new { |x| x * x }
puts square.call(5)
puts square.(6) # alternate call syntax
# Lambda - stricter arity, returns from itself not the caller
add = ->(a, b) { a + b }
puts add.call(1, 2)
# Method taking a block explicitly
def apply(a, b)
yield(a, b)
end
puts apply(4, 5) { |x, y| x * y }
# & to convert block <-> proc
def capture(&blk); blk.call; end
capture { puts "captured" }
arr = %w[apple banana cherry]
up = arr.map(&:upcase) # symbol to proc
puts up.inspectExplanation
Blocks are nameless chunks of code implicitly passed to methods and invoked with yield. Procs and lambdas wrap blocks as first-class objects with different return and arity rules: lambdas check argument count strictly and return only from themselves. The & operator converts between blocks and Procs, and Symbol#to_proc enables the concise &:upcase idiom.
More Ruby Snippets
Classes and Modules
Define classes with inheritance, mix in modules, and add class methods.
Iterators
Use each, map, select, reduce, group_by, and lazy enumerators.
Strings
Interpolate, trim, split, replace, and pattern-match strings.
Hashes
Build, default, transform, merge, and group with Hash.
Metaprogramming
Define methods dynamically, intercept with method_missing, and build DSLs.
Error Handling
Raise and rescue typed exceptions with ensure and retry.