Blocks
In this page:
Blocks
Almost any Ruby method call can accept an attached block, written with { ... } or do ... end, which the method can run zero or more times using yield. Blocks are how iteration methods like each and map receive the logic to run per element. Unlike a Proc or Lambda, a block is not itself an object -- it's syntax tied directly to a single method call.
Note: Use { } for short, single-line blocks and do...end for longer, multi-line blocks -- this is the community style convention.
Example: Blocks
[1, 2, 3].each { |n| puts "Value: #{n}" }
[1, 2, 3].each do |n|
doubled = n * 2
puts "Doubled: #{doubled}"
end
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: