Consider this Ruby code that uses define_method to create methods dynamically. What will it print?
class Greeter [:hello, :goodbye].each do |method_name| define_method(method_name) do |name| "#{method_name.to_s.capitalize}, #{name}!" end end end g = Greeter.new puts g.hello("Alice") puts g.goodbye("Bob")
Look at how define_method uses the symbol and string interpolation.
The define_method creates methods named hello and goodbye. Each method returns a string with the method name capitalized and the given name. So it prints 'Hello, Alice!' and 'Goodbye, Bob!'.
Which of these best explains why metaprogramming is powerful in Ruby?
Think about what it means to change code while the program is running.
Metaprogramming lets Ruby programs create or change methods and classes while running. This makes code more flexible and reduces repetition (DRY = Don't Repeat Yourself).
This Ruby code tries to create getter methods dynamically but raises an error. What is the cause?
class Person [:name, :age].each do |attr| define_method(attr) do @attr end end end p = Person.new p.name
Check what @attr means inside the method.
The code uses @attr literally, but it should use the variable attr to build the instance variable name dynamically, like instance_variable_get("@#{attr}").
Which Ruby code correctly defines a method greet that takes a name parameter and returns a greeting?
Remember the syntax for define_method with a block and parameters.
Option D uses the correct syntax: define_method(:greet) { |name| ... }. Other options have syntax errors.
This Ruby code uses method_missing to handle undefined methods. What will it print?
class Dynamic def method_missing(name, *args) if name.to_s.start_with?("say_") word = name.to_s.split("_")[1] "You said: #{word} with args: #{args.join(", ")}" else super end end end d = Dynamic.new puts d.say_hello("world") puts d.say_goodbye("everyone") puts d.unknown_method
Look at how method_missing handles method names starting with say_.
Methods starting with say_ are handled and print a message. Other methods call super, raising NoMethodError.