0
0
Rubyprogramming~20 mins

Constants in classes in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Constants Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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
Anil
B10
C20
DNameError
Attempts:
2 left
💡 Hint
Remember that constants inside a nested class override outer constants with the same name.
Predict Output
intermediate
2: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
A0
Bnil
CNameError
D5
Attempts:
2 left
💡 Hint
Use the scope resolution operator to access constants from outer classes.
Predict Output
advanced
2: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
ANameError
Bnil
C"parent"
D"child"
Attempts:
2 left
💡 Hint
Constants inside nested classes do not inherit from the outer class or its ancestors automatically.
Predict Output
advanced
2: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
A200
B100
CNameError
Dnil
Attempts:
2 left
💡 Hint
Using M::CONST accesses the constant defined in the module M, not the class C.
🧠 Conceptual
expert
2: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
AWarning and 2
B1
C2
DError
Attempts:
2 left
💡 Hint
Ruby allows constant reassignment but warns about it.