Skip to main content

Command Palette

Search for a command to run...

Ruby: What is class instance variable

Updated
1 min read

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.

18 views

More from this blog

Tenzin Chemi

15 posts

Software writer out of curiosity. 322D 9687 C273 50CE 5F39 7A03 0D27 F9C6 BDAF B6D3