Complete the code to define a method dynamically using define_method.
class Greeting [1] :hello do puts 'Hello, world!' end end
def instead of define_method for dynamic method creation.The define_method lets you create methods dynamically, which is a key part of Ruby metaprogramming.
Complete the code to catch calls to undefined methods using method_missing.
class Dynamic def [1](method_name, *args) puts "You called #{method_name} with #{args.inspect}" end end
method_missing with respond_to_missing? or send.method_missing is a Ruby hook that lets you handle calls to methods that don't exist, enabling dynamic behavior.
Fix the error in the code to dynamically create getter methods using define_method.
class Person [:name, :age].each do |attr| [1] attr do @#{attr} end end end
def inside a block, which is invalid syntax.define_method is used here to create getter methods dynamically for each attribute.
Fill both blanks to create a method that responds to any undefined method by printing its name and arguments.
class Catcher def [1](method_name, *args) puts "Called #{method_name} with #{args[2]" end end
to_s instead of inspect for argument display.method_missing catches undefined method calls, and inspect shows the arguments nicely.
Fill all three blanks to create a dynamic attribute writer method using define_method.
class DynamicAttr [:title, :author, :year].each do |attr| [1] "#{attr}=" do |value| @[2] = [3] end end end
attr_accessor instead of define_method for dynamic method creation.This code dynamically creates setter methods for each attribute. define_method defines the method, attr is the attribute name used for the instance variable, and value is the argument assigned to the instance variable.