0
0
Rubyprogramming~20 mins

Class instance variables as alternative in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Class Instance Variables Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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
A0
BError: undefined method `+' for nil:NilClass
C2
Dnil
Attempts:
2 left
💡 Hint
Class instance variables belong to the class itself, not instances.
Predict Output
intermediate
2: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
A1\n2
B1\nnil
Cnil\n2
D2\n1
Attempts:
2 left
💡 Hint
Class variables start with @@ and are shared across the class hierarchy.
🔧 Debug
advanced
2: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
AClass instance variables are not accessible inside instance methods by default.
BSyntax error because @value is not initialized in constructor.
CThe method value is missing a return statement.
DInstance method accesses instance variable of object, but @value is only set on class, not instance.
Attempts:
2 left
💡 Hint
Class instance variables belong to the class object, not to instances.
🧠 Conceptual
advanced
2: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
Achild data\nchild data
Bparent data\nchild data
Cparent data\nparent data
Dnil\nnil
Attempts:
2 left
💡 Hint
Class instance variables are not shared between parent and child classes.
📝 Syntax
expert
2: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
A
class Test
  @var = 5
  def get_var
    self.@var
  end
end
B
class Test
  @@var = 5
  def self.get_var
    @var
  end
end
C
class Test
  @var = 5
  def self.get_var
    @var
  end
end
D
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.