Challenge - 5 Problems
Class-Level Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Understanding class variables and instance variables
What is the output of this Ruby code?
class Counter
@@count = 0
def initialize
@@count += 1
end
def self.count
@@count
end
end
c1 = Counter.new
c2 = Counter.new
puts Counter.countRuby
class Counter @@count = 0 def initialize @@count += 1 end def self.count @@count end end c1 = Counter.new c2 = Counter.new puts Counter.count
Attempts:
2 left
💡 Hint
Class variables are shared across all instances of the class.
✗ Incorrect
The class variable @@count is shared by all instances. Each time a new object is created, @@count increases by 1. After creating two objects, @@count is 2.
❓ Predict Output
intermediate2:00remaining
Difference between class instance variable and class variable
What will this Ruby code print?
class Example
@value = 10
def self.value
@value
end
def value
@value
end
end
obj = Example.new
puts Example.value
puts obj.valueRuby
class Example @value = 10 def self.value @value end def value @value end end obj = Example.new puts Example.value puts obj.value
Attempts:
2 left
💡 Hint
Class instance variables belong to the class object, not instances.
✗ Incorrect
The class instance variable @value is set to 10 for the class object. The class method returns 10. The instance method looks for @value in the instance, which is nil.
🔧 Debug
advanced2:30remaining
Why does this class variable behave unexpectedly?
Consider this Ruby code:
What is the output and why?
class Parent
@@var = 1
def self.var
@@var
end
end
class Child < Parent
@@var = 2
end
puts Parent.var
puts Child.varWhat is the output and why?
Ruby
class Parent @@var = 1 def self.var @@var end end class Child < Parent @@var = 2 end puts Parent.var puts Child.var
Attempts:
2 left
💡 Hint
Class variables are shared between parent and child classes.
✗ Incorrect
In Ruby, class variables (@@var) are shared by a class and all its subclasses. Changing @@var in Child changes it for Parent too.
📝 Syntax
advanced1:30remaining
Identify the syntax error in class-level method definition
Which option contains a syntax error in defining a class method in Ruby?
Attempts:
2 left
💡 Hint
Class methods are defined on the class object, not on method names.
✗ Incorrect
Option A tries to define a method named 'method_name.self' which is invalid syntax in Ruby.
🚀 Application
expert3:00remaining
Predict the output of class instance variable with inheritance
What will this Ruby code print?
class A
@var = 1
def self.var
@var
end
end
class B < A
@var = 2
end
puts A.var
puts B.varRuby
class A @var = 1 def self.var @var end end class B < A @var = 2 end puts A.var puts B.var
Attempts:
2 left
💡 Hint
Class instance variables are not shared between parent and child classes.
✗ Incorrect
Each class has its own @var. A.var returns 1, B.var returns 2 because B sets its own @var.