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

Blocks

In this page:

  1. Blocks

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
🔒

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.