Bird
0
0

What will be the output of the following Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - Classes and Objects
What will be the output of the following Ruby code?
class Dog
  def speak
    self.class
  end
end

fido = Dog.new
puts fido.speak
ADog
B#<Class:Dog>
Cfido
DObject
Step-by-Step Solution
Solution:
  1. Step 1: Understand what self is inside speak

    Inside the instance method speak, self is the instance fido.
  2. Step 2: Evaluate self.class

    Calling class on the instance returns its class, which is Dog.
  3. Final Answer:

    Dog -> Option A
  4. Quick Check:

    self.class in instance method = class name [OK]
Quick Trick: self.class inside instance method returns the object's class [OK]
Common Mistakes:
  • Thinking self.class returns the instance
  • Confusing class with object name
  • Expecting output to be an object instead of class name

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes