RSS
 

Ruby Class Variables in the main context

05 Sep

Since ruby class variables belong to the class hierarchy, all objects in that class hierarchy all the way up to ruby’s main object, share the same class variable. This could lead to unexpected behavior, especially since the class variable can be modified in the main context. See below modifying @@name in the main context changes its value on all objects.

class Cat
end
 
class Tiger < Cat
  def me
    @@name = 'tiger'
  end
 
  def show
    @@name
  end
end
 
tiger = Tiger.new
 
tiger.me
#=> "tiger"
 
tiger.show
#=> "tiger" 
 
class Cat
  def me
    @@name = 'cat'
  end
 
  def show
    @@name
  end 
end
 
cat = Cat.new
 
cat.me
#=> "cat" 
 
cat.show
#=> "cat"
 
tiger.show
#=> "cat"
 
@@name = 'animal'
#=> "animal" 
 
cat.show
#=> "animal"
 
tiger.show
#=> "animal"
 
 
 
Premium Wordpress Plugin