Menu
Coddy logo textTech

do..end vs Braces

Part of the Logic & Flow section of Coddy's Ruby journey — lesson 16 of 56.

Ruby gives you two ways to write a block. They mean the same thing, but each has a preferred use case.

do...end is for multi-line blocks:

[1, 2, 3].each do |n|
  doubled = n * 2
  puts "#{n} -> #{doubled}"
end

Curly braces { ... } are for single-line blocks, short, expression-shaped:

[1, 2, 3].each { |n| puts n * 2 }

The two have slightly different precedence, but the rule learners need is the style one: braces for one-liners, do...end for multi-line.

Both forms can return a value. The block's last expression is what gets passed back to methods like map:

[1, 2, 3].map { |n| n * 10 }    # [10, 20, 30]
[1, 2, 3].map do |n|
  n * 10
end                              # [10, 20, 30]
challenge icon

Challenge

Easy

Read a comma-separated list of integers from input. Print two lines:

  1. Each number doubled, joined with , . Use the brace form of map.
  2. The string "<n> squared is <n*n>" for each number, one per line. Use the do...end form of each.

For input 1,2,3, the output is:

2, 4, 6
1 squared is 1
2 squared is 4
3 squared is 9

Cheat sheet

Ruby blocks have two syntaxes:

Curly braces { ... } for single-line blocks:

[1, 2, 3].map { |n| n * 2 }  # [2, 4, 6]

do...end for multi-line blocks:

[1, 2, 3].each do |n|
  doubled = n * 2
  puts "#{n} -> #{doubled}"
end

Both forms return the block's last expression (used by methods like map).

Try it yourself

numbers = gets.chomp.split(",").map(&:to_i)

# TODO: line 1, doubled, brace form of map, joined with ", "
# TODO: lines 2..n, squares, do...end form of each
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow