Blocks – code as a gift
You've been using blocks since lesson 6 – now let's look behind the curtain. A method receives a block and runs it with yield; block_given? tells you whether one arrived. That's how you build “wrapper” methods like this stopwatch:
def with_timing(name)
start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
result = yield
ms = (Process.clock_gettime(Process::CLOCK_MONOTONIC) - start) * 1000
puts "#{name}: #{ms.round(1)} ms"
result
end
with_timing("sum") { (1..100_000).sum }A block is not an object – but you can make it one. proc and lambda wrap code into variables. The differences: a lambda checks its argument count strictly and return leaves only the lambda; a proc is relaxed about both. And &:to_s is the shorthand for “turn this symbol into a block”:
double = ->(x) { x * 2 }
[double.call(21), double.(5), [1, 2, 3].map(&:to_s)]Lambdas are closures: they carry their environment with them. Perfect for timelog report formats – each format is a small packaged program:
formats = {
text: ->(e) { "#{e[:project].ljust(10)} #{e[:hours]}h" },
csv: ->(e) { "#{e[:project]};#{e[:hours]}" }
}
entry = { project: "ProjectX", hours: 3.5 }
formats[:csv].call(entry)Task: Write
each_project(entries): the method groups the entries by project and hands via yield each pair (project, list) to the block – like each, one floor up.# def each_project(entries)
# ... group_by ... yield ...
# end
# Test:
# each_project([{ project: "A", hours: 1.0 }]) do |project, list|
# puts "#{project}: #{list.length} entries"
# end