Ruby class instance variable vs. class variable

I read https://stackoverflow.com/questions/826734/when-do-ruby-instance-variables-get-set but I’m of two minds when to use class instance variables.

Class variables are shared by all objects of a class, Instance variables belong to one object. There’s not much room left to use class instance variables if we have class variables.

Could someone explain the difference between these two and when to use them?

Here’s a code example:

class S
  @@k = 23
  @s = 15
  def self.s
    @s
  end
  def self.k
     @@k
  end

end
p S.s #15
p S.k #23

Update: I understand now! Class Instance Variables are not passed along the inheritance chain.

8 Answers
8

Leave a Comment