Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - Metaprogramming Fundamentals
What will be the output of this Ruby code?
MyClass = Class.new do
  def greet
    "Hi"
  end
end

obj = MyClass.new
puts obj.greet
AHi
BHello
CError: undefined method greet
Dnil
Step-by-Step Solution
Solution:
  1. Step 1: Understand class creation and method definition

    The code creates a new class with a method greet returning "Hi".
  2. Step 2: Create instance and call method

    Creating an instance obj and calling obj.greet returns "Hi" which is printed.
  3. Final Answer:

    Hi -> Option A
  4. Quick Check:

    Method greet returns "Hi" [OK]
Quick Trick: Method returns string; puts prints it [OK]
Common Mistakes:
  • Expecting 'Hello' instead of 'Hi'
  • Thinking method is undefined
  • Confusing return value with nil

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes