Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q4 of 15
Ruby - Metaprogramming Fundamentals
What will be the output of this Ruby code?
class Demo
  def self.create_method(name)
    define_method(name) { "Hello, #{name}!" }
  end

  create_method(:greet)
end

d = Demo.new
puts d.greet
ANoMethodError
BHello, name!
CHello, Demo!
DHello, greet!
Step-by-Step Solution
Solution:
  1. Step 1: Understand method creation

    The class method create_method tries to define an instance method using define_method, but define_method is a private instance method of Module, so calling it directly inside a class method without receiver causes an error.
  2. Step 2: Reason about output

    Since define_method is called without receiver inside a class method, it raises NoMethodError.
  3. Final Answer:

    NoMethodError -> Option A
  4. Quick Check:

    define_method called incorrectly in class method = NoMethodError [OK]
Quick Trick: define_method must be called in instance context or with proper receiver [OK]
Common Mistakes:
  • Assuming define_method works inside class methods without receiver
  • Expecting method to be defined successfully
  • Confusing class and instance method scopes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes