0
0
Rubyprogramming~30 mins

DSL building patterns in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Building a Simple DSL in Ruby
📖 Scenario: Imagine you want to create a small language inside Ruby to describe a recipe. This language will let you write recipes in a way that looks like plain English but runs as Ruby code.
🎯 Goal: You will build a simple Domain Specific Language (DSL) in Ruby to describe a recipe with ingredients and steps. You will then print the recipe in a readable format.
📋 What You'll Learn
Create a class called Recipe to hold ingredients and steps
Add a method called ingredient to add ingredients with name and quantity
Add a method called step to add instructions
Use a block to define the recipe content
Print the recipe with ingredients and steps in order
💡 Why This Matters
🌍 Real World
DSLs help make complex tasks easier by creating small languages tailored to specific problems, like writing recipes, configuring apps, or describing workflows.
💼 Career
Understanding DSL building patterns is useful for Ruby developers working on frameworks, testing tools, or configuration systems where readable and flexible code is important.
Progress0 / 4 steps
1
Create the Recipe class with storage
Create a class called Recipe with two instance variables: @ingredients and @steps. Initialize both as empty arrays inside the initialize method.
Ruby
Need a hint?

Use @ingredients = [] and @steps = [] inside the initialize method.

2
Add methods to add ingredients and steps
Add two methods inside the Recipe class: ingredient(name, quantity) which adds a hash with keys :name and :quantity to @ingredients, and step(description) which adds the description string to @steps.
Ruby
Need a hint?

Use @ingredients << { name: name, quantity: quantity } and @steps << description inside the methods.

3
Add a class method to build the recipe with a block
Add a class method self.build that takes a block. Inside it, create a new Recipe instance, yield it to the block, and return the instance.
Ruby
Need a hint?

Use yield(recipe) to run the block with the recipe object.

4
Print the recipe ingredients and steps
Add a method print_recipe inside the Recipe class that prints "Ingredients:" followed by each ingredient's quantity and name on separate lines, then prints "Steps:" followed by each step numbered starting from 1. Then create a recipe using Recipe.build with these exact ingredients and steps:
ingredient("Flour", "2 cups"), ingredient("Sugar", "1 cup"), step("Mix ingredients"), step("Bake for 30 minutes"). Finally, call print_recipe on the created recipe.
Ruby
Need a hint?

Use puts to print lines. Use each to loop through ingredients and steps. Use each_with_index to number steps.