← Back to Ruby Course | Chapter 7: Methods | Lesson 6 of 7

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:

  1. Blocks
Syntax
ruby
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

markup
[1, 2, 3].each { |n| puts "Value: #{n}" }

[1, 2, 3].each do |n|
  doubled = n * 2
  puts "Doubled: #{doubled}"
end
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
  1. Writing puts [1, 2, 3].each { ... } where the braces bind to [1, 2, 3].each, but with do ... end the block binds to puts.
  2. Expecting variables defined inside the block to exist after it, when block-local variables disappear.
  3. Using { } for multi-line blocks and do...end for 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.