Challenge - 5 Problems
Ruby Constants Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of accessing a constant inside a nested class
What is the output of this Ruby code?
Ruby
class Outer CONST = 10 class Inner CONST = 20 def self.show CONST end end end puts Outer::Inner.show
Attempts:
2 left
💡 Hint
Remember that constants inside a nested class override outer constants with the same name.
✗ Incorrect
The Inner class defines its own CONST as 20, so Outer::Inner.show returns 20.
❓ Predict Output
intermediate2:00remaining
Accessing a constant from an outer class
What will this Ruby code print?
Ruby
class A VALUE = 5 class B def self.get_value A::VALUE end end end puts A::B.get_value
Attempts:
2 left
💡 Hint
Use the scope resolution operator to access constants from outer classes.
✗ Incorrect
A::VALUE is 5, so A::B.get_value returns 5.
❓ Predict Output
advanced2:00remaining
Constant lookup with inheritance and nesting
What is the output of this Ruby code?
Ruby
class Parent CONST = 'parent' end class Child < Parent CONST = 'child' class Nested def self.value CONST end end end puts Child::Nested.value
Attempts:
2 left
💡 Hint
Constants inside nested classes do not inherit from the outer class or its ancestors automatically.
✗ Incorrect
Nested class does not have CONST defined and does not inherit from Child, so CONST is undefined and raises NameError.
❓ Predict Output
advanced2:00remaining
Constant resolution with explicit scope
What does this Ruby code print?
Ruby
module M CONST = 100 class C CONST = 200 def self.show M::CONST end end end puts M::C.show
Attempts:
2 left
💡 Hint
Using M::CONST accesses the constant defined in the module M, not the class C.
✗ Incorrect
M::CONST is 100, so M::C.show returns 100.
🧠 Conceptual
expert2:00remaining
Behavior of constant reassignment in Ruby classes
Consider this Ruby code snippet. What will be the output and why?
class X
CONST = 1
CONST = 2
def self.value
CONST
end
end
puts X.value
Attempts:
2 left
💡 Hint
Ruby allows constant reassignment but warns about it.
✗ Incorrect
Ruby prints a warning about constant reassignment but the value is updated to 2, so output is 2 with a warning.