ruby · level 3 · unit 5 · lesson 1
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Two methods called chef. Which one answers?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
class Kitchen
def chef
"Kitchen chef"
end
end
def chef
"Top-level chef"
end
puts chef
Kitchen.new.instance_eval { puts chef }
puts self
your turn
Your turn. Write a shopping list in bare words.
Fill the first blank with the method that runs the block with the list as self. Then choose something to buy two of.
fix it
Nobody gets invited to the party. Fix the class.
- The error says
inviteis undefined for main. Who isselfinside the block? block.callruns the block withselfstill the top-level object, not the party.- Change line 3 to
instance_eval(&block), then press run.
nailed it
you changed who is listening. :D
- A method name with no dot is sent to
self. instance_evalruns a block with your object asself.- That one trick powers most Ruby DSLs.
new words in your collection
- DSL
- self
- instance_eval
This lesson isn’t saved. A free account remembers every lesson you finish.