Ruby: What is class instance variable
Class instance variables are variables that have punctual prefix @
and are used inside class definition.
class Shape
@count = 6
def instance_method_x
puts "No: '#{@count}'"
end
class << self
def class_method_x
puts "No: '#{@count}'"
end
end
end
They are not visible to instance methods
Shape.new.instance_method_x #=> No: ''
They are visible to class methods
Shape.class_method_x #=> No: '6'
You can expose class instance variable via attr_reader
class Shape
@count = 6
class << self
attr_reader :count
end
end
# With that, you can access
$> Shape.count
#=> 6
Other points:
They can be replaced by
@@
class variables.They can be confusing with ordinary instance variables. Without the punctuation
@@
or@
, it can be difficult to understand whether the variable is associated with class or instance.