ruby · level 3 · unit 5 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Blocks inside blocks build a , one builder per level.
A menu has sections, and each section has items. That shape is a tree: each part can hold smaller parts. A DSL can mirror it with blocks, a block inside a block, so the code looks like the menu it describes.
Each level gets its own builder. section makes a Section object and runs the inner block on it with instance_eval, so bare words like item go to the section, not the menu. When the inner block ends, self goes back to being the menu.
class Section
def item(name, price)
puts " #{name}: #{price} pounds"
end
end
class Menu
def section(title, &block)
puts title.upcase
Section.new.instance_eval(&block)
end
end
Menu.new.instance_eval do
section("Cakes") { item "Scone", 3 }
end Each builder only understands the words for its own level, which keeps every part of the DSL small.
guess first
An item outside any section. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
class Section
def item(name, price)
puts " #{name}: #{price}"
end
end
def section(title, &block)
puts title
Section.new.instance_eval(&block)
end
section("Drinks") { item "Tea", 2 }
item "Scone", 3
your turn
Your turn. Describe an album and one of its tracks.
Type an album name in the first blank and a track on it in the second, then press run.
fix it
Ruby will not even start this menu. Fix it.
- It is a SyntaxError, so look closely at how line 13 is written.
- Without brackets, a
{ }block tries to attach to the nearest thing on its left, which is the string "Drinks". - Put brackets round the title:
section("Drinks") { item "Tea", 2 }.
nailed it
you built a dsl with levels. :D
- Nested blocks let a DSL mirror the shape of a tree.
- Each level gets its own builder with its own words.
- With
{ }blocks, put brackets round the arguments.
new words in your collection
- tree
- nested
This lesson isn’t saved. A free account remembers every lesson you finish.