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}"
endCurly 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
EasyRead a comma-separated list of integers from input. Print two lines:
- Each number doubled, joined with
,. Use the brace form ofmap. - The string
"<n> squared is <n*n>"for each number, one per line. Use thedo...endform ofeach.
For input 1,2,3, the output is:
2, 4, 6
1 squared is 1
2 squared is 4
3 squared is 9Cheat 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}"
endBoth 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String Methods OverviewString InterpolationIterating Over StringsSplit and JoinRecap - String Weaver4Blocks, Procs & Lambdas
What is a Block?do..end vs BracesThe yield KeywordBlock ParametersProcs and LambdasRecap - Custom Iterator7Hashes Part 2
Hash.new with DefaultsIterating HashesNested HashesMerging and TransformingRecap - Frequency Counter10Project - Student Records
Project OverviewAdd Student5Enumerable Powerhouse
Select and RejectChaining MapReduce / Injectcount, all?, any?, none?group_by and partitionsort_by, min_by, max_byRecap - Data Pipeline8Advanced Decision Making
Case with Classes & RegexMulti-value whenTernary OperatorInline if / unlessRecap - Grade Classifier