Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q5 of 15
Ruby - Class Methods and Variables
What will be the output of this Ruby code?
class Bird
  @count = 5

  def self.count
    @count
  end
end

class Parrot < Bird
  @count = 10
end

puts Bird.count
puts Parrot.count
A5\n10
B10\n10
C5\n5
Dnil\nnil
Step-by-Step Solution
Solution:
  1. Step 1: Understand class instance variables are not shared

    Bird and Parrot each have their own @count variable.
  2. Step 2: Check values

    Bird.count returns 5, Parrot.count returns 10 as set separately.
  3. Final Answer:

    5\n10 -> Option A
  4. Quick Check:

    Separate class instance vars in inheritance = 5\n10 [OK]
Quick Trick: Class instance vars are separate per class, not inherited [OK]
Common Mistakes:
  • Assuming subclass shares class instance variables
  • Expecting both outputs to be 10
  • Confusing with class variables which are shared

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes