Blocks
A block is a chunk of code you hand to a method to run at the right moment, like giving a friend a note to read out. It sits right after the method call in braces or do and end.
In this page:
Syntax
collection.method_name { |item| expression }
collection.method_name do |item|
# body
end
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Writing
puts [1, 2, 3].each { ... }where the braces bind to[1, 2, 3].each, but withdo ... endthe block binds toputs. - Expecting variables defined inside the block to exist after it, when block-local variables disappear.
- Using
{ }for multi-line blocks anddo...endfor one-liners, when the convention is the other way round.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: