Module 02 Β· Collections & Blocks β Lesson 3 of 6 Β· ~11 min
Blocks: each
A block is just code you hand to a method
This is Ruby's real superpower, and it's simpler than it sounds: a block is a chunk of code attached to a method call, which the method runs however many times it wants β once per item, once total, or not at all. You've already been passed the idea in Swift's trailing closures ([1,2,3].map { $0 * 2 }); a Ruby block is the same concept, built into the language's core syntax instead of being "just another closure value."
There are two ways to write one β a do ... end form for multiple lines, and a { ... } form for one line:
walkers.each do |walker|
puts "Walker: #{walker}"
end
walkers.each { |walker| puts walker }Same block, two spellings. The stuff between the pipes β |walker| β names the parameter the block receives each time it runs, same job as a closure's parameter list.