0
0
Rubyprogramming~10 mins

DSL building patterns in Ruby - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a simple DSL method that yields to a block.

Ruby
def my_dsl_method
  [1]
end
Drag options to blanks, or click blank then click option'
Ayield
Breturn
Cputs
Dbreak
Attempts:
3 left
💡 Hint
Common Mistakes
Using return instead of yield stops the method without running the block.
Using puts prints text but does not execute the block.
2fill in blank
medium

Complete the code to define a DSL method that takes a block and instance_eval's it.

Ruby
def configure
  instance_eval [1]
end
Drag options to blanks, or click blank then click option'
A&block
Bblock
Cyield
Dself
Attempts:
3 left
💡 Hint
Common Mistakes
Passing block without & causes an error because block is not defined as a variable.
Using yield here does not work with instance_eval.
3fill in blank
hard

Fix the error in the DSL method that tries to store configuration values.

Ruby
class Config
  def initialize
    @settings = {}
  end

  def set(key, value)
    @settings[[1]] = value
  end
end
Drag options to blanks, or click blank then click option'
Avalue
Bkey.to_s
Ckey.to_sym
Dself
Attempts:
3 left
💡 Hint
Common Mistakes
Using key.to_s may cause inconsistency if keys are symbols elsewhere.
Using value as a key is incorrect.
4fill in blank
hard

Fill both blanks to create a DSL method that stores a block and later calls it with instance_eval.

Ruby
class Builder
  def initialize
    @block = nil
  end

  def define(&[1])
    @block = [2]
  end

  def run
    instance_eval(&@block)
  end
end
Drag options to blanks, or click blank then click option'
Ablock
Bproc
Dlambda
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for the block parameter and the stored variable causes errors.
Using proc or lambda without defining them causes errors.
5fill in blank
hard

Fill all three blanks to create a DSL method that builds a hash from keys and values with a condition.

Ruby
def build_hash(items)
  result = { [1] => [2] for [3] in items if [2].length > 3 }
  result
end
Drag options to blanks, or click blank then click option'
Aitem
Bvalue
Ckey
Dk
Attempts:
3 left
💡 Hint
Common Mistakes
Using the same variable name for key and value causes confusion.
Not matching the variable names in the condition causes errors.