Elmor Elmor - 4 months ago 16
Ruby Question

Ruby class instance variable vs. class variable

I've read this thread When do Ruby instance variables get set? but i'm in two minds when to use class instance variables.

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

Could you explain to me difference between these two and when to use them?
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! Thanks to all!

Answer

Instance variable on a class:

class Parent
  @things = []
  def self.things
    @things
  end
  def things
    self.class.things
  end
end

class Child < Parent
  @things = []
end

Parent.things << :car
Child.things  << :doll
mom = Parent.new
dad = Parent.new

p Parent.things #=> [:car]
p Child.things  #=> [:doll]
p mom.things    #=> [:car]
p dad.things    #=> [:car]

Class variable:

class Parent
  @@things = []
  def self.things
    @@things
  end
  def things
    @@things
  end
end

class Child < Parent
end

Parent.things << :car
Child.things  << :doll

p Parent.things #=> [:car,:doll]
p Child.things  #=> [:car,:doll]

mom = Parent.new
dad = Parent.new
son1 = Child.new
son2 = Child.new
daughter = Child.new

[ mom, dad, son1, son2, daughter ].each{ |person| p person.things }
#=> [:car, :doll]
#=> [:car, :doll]
#=> [:car, :doll]
#=> [:car, :doll]
#=> [:car, :doll]

With an instance variable on a class (not on an instance of that class) you can store something common to that class without having sub-classes automatically also get them (and vice-versa). With class variables, you have the convenience of not having to write self.class from an instance object, and (when desirable) you also get automatic sharing throughout the class hierarchy.

Comments