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'

Other points:

  • They can be used as class variables like we did with @@ .

  • 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.