Complete the code to define a simple DSL method that yields to a block.
def my_dsl_method [1] end
return instead of yield stops the method without running the block.puts prints text but does not execute the block.The yield keyword calls the block passed to the method, which is essential in DSLs to execute user-defined code.
Complete the code to define a DSL method that takes a block and instance_eval's it.
def configure instance_eval [1] end
block without & causes an error because block is not defined as a variable.yield here does not work with instance_eval.The &block syntax passes the block as a Proc object, which instance_eval can execute in the context of the current object.
Fix the error in the DSL method that tries to store configuration values.
class Config def initialize @settings = {} end def set(key, value) @settings[[1]] = value end end
key.to_s may cause inconsistency if keys are symbols elsewhere.value as a key is incorrect.Converting the key to a symbol ensures consistent keys in the settings hash, which is a common practice in DSLs.
Fill both blanks to create a DSL method that stores a block and later calls it with instance_eval.
class Builder def initialize @block = nil end def define(&[1]) @block = [2] end def run instance_eval(&@block) end end
proc or lambda without defining them causes errors.The method takes a block parameter named block and stores it in @block. Later, instance_eval runs this block in the object's context.
Fill all three blanks to create a DSL method that builds a hash from keys and values with a condition.
def build_hash(items) result = { [1] => [2] for [3] in items if [2].length > 3 } result end
This code builds a hash where k is the key and value is the value from items. It includes only those where the value's length is greater than 3.