Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q4 of 15
Ruby - Class Methods and Variables
What will be the output of this Ruby code?
class Animal
  LEGS = 4
  def legs
    LEGS
  end
end
puts Animal::LEGS
puts Animal.new.legs
A4\n4
BLEGS\nLEGS
CError: uninitialized constant
Dnil\nnil
Step-by-Step Solution
Solution:
  1. Step 1: Understand constant access in class and instance

    Animal::LEGS accesses the constant directly; instance method legs returns the constant.
  2. Step 2: Predict output

    Both print 4 because LEGS is 4 in both contexts.
  3. Final Answer:

    4\n4 -> Option A
  4. Quick Check:

    Constant access = 4 and 4 [OK]
Quick Trick: Constants accessible via class and instance methods [OK]
Common Mistakes:
  • Expecting error accessing constant from instance
  • Confusing constant name with string output
  • Assuming nil if accessed from instance

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes