Bird
0
0

How would you modify this DSL builder to allow nested blocks for steps?

hard📝 Application Q8 of 15
Ruby - Advanced Metaprogramming
How would you modify this DSL builder to allow nested blocks for steps?
class Builder
  def initialize
    @steps = []
  end
  def step(name, &block)
    if block
      nested_builder = Builder.new
      nested_builder.instance_eval(&block)
      @steps << {name => nested_builder.steps}
    else
      @steps << name
    end
  end
end
ARemove &block from step method to simplify calls
BUse yield instead of instance_eval for nested blocks
CAdd a steps method to expose @steps for nested access
DInitialize @steps as a hash instead of array
Step-by-Step Solution
Solution:
  1. Step 1: Identify nested block handling

    Nested blocks create new Builder instances and store nested steps.
  2. Step 2: Expose nested steps

    Adding a steps method allows access to @steps for nesting to work properly.
  3. Final Answer:

    Add a steps method to expose @steps for nested access -> Option C
  4. Quick Check:

    Nested DSL needs accessor for internal steps [OK]
Quick Trick: Expose internal state with methods for nested DSL blocks [OK]
Common Mistakes:
  • Removing block parameter breaks nesting
  • Using yield loses context for nested builder
  • Changing @steps to hash breaks ordered steps

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes