Challenge - 5 Problems
Ruby Class Instance Variables Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of class instance variable usage
What is the output of this Ruby code using class instance variables?
Ruby
class Counter @count = 0 def self.increment @count += 1 end def self.count @count end end Counter.increment Counter.increment puts Counter.count
Attempts:
2 left
💡 Hint
Class instance variables belong to the class itself, not instances.
✗ Incorrect
The class instance variable @count is initialized to 0. Each call to increment adds 1. After two increments, count returns 2.
❓ Predict Output
intermediate2:00remaining
Difference between class variable and class instance variable
What will this Ruby code output?
Ruby
class Example @@var = 1 @var = 2 def self.class_var @@var end def self.class_instance_var @var end end puts Example.class_var puts Example.class_instance_var
Attempts:
2 left
💡 Hint
Class variables start with @@ and are shared across the class hierarchy.
✗ Incorrect
The class variable @@var is 1. The class instance variable @var is 2. Both are accessed correctly by their methods.
🔧 Debug
advanced2:00remaining
Why does this class instance variable return nil?
This Ruby code prints nil. Why?
Ruby
class Sample @value = 10 def value @value end end obj = Sample.new puts obj.value
Attempts:
2 left
💡 Hint
Class instance variables belong to the class object, not to instances.
✗ Incorrect
The @value set on the class is different from the @value on the instance. The instance's @value is never set, so it is nil.
🧠 Conceptual
advanced2:00remaining
Class instance variables and inheritance behavior
Given this Ruby code, what will be the output?
Ruby
class Parent @data = 'parent data' def self.data @data end end class Child < Parent @data = 'child data' end puts Parent.data puts Child.data
Attempts:
2 left
💡 Hint
Class instance variables are not shared between parent and child classes.
✗ Incorrect
Each class has its own @data variable. Parent.data returns 'parent data', Child.data returns 'child data'.
📝 Syntax
expert2:00remaining
Identify the syntax error in class instance variable usage
Which option contains a syntax error when trying to define and access a class instance variable?
Ruby
class Test @var = 5 def self.get_var @var end end
Attempts:
2 left
💡 Hint
Class instance variables are accessed in class methods, not instance methods.
✗ Incorrect
Option A contains a syntax error: 'self.@var' is invalid Ruby syntax. Instance variables (including class instance variables in class methods) cannot be accessed using 'self.@var'; use just '@var'.