×

ruby · level 3 · unit 5 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.