×

ruby · level 3 · unit 5 · lesson 1

  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

runs a block with a different .

A , short for domain-specific language, is a mini-language built for one job. Rails routes, test files and build scripts are all DSLs written in plain Ruby. They read like a list of instructions, such as title "Spring sale", with no dots and no objects in sight.

The trick is self, the object running the current code. A bare method name, written with no dot in front, is sent to self. instance_eval runs a block with a chosen object as self, so every bare method name inside the block becomes a call on that object.

class Poster
  def title(text)
    puts text.upcase
  end
  def detail(text)
    puts "* #{text}"
  end
end
Poster.new.instance_eval do
  title "Spring sale"
  detail "20% off everything"
  detail "Ends Sunday"
end

Method calls without brackets, like title "Spring sale", are ordinary Ruby, which is why a DSL can read like plain instructions.