Mar 20

Why class variables in Ruby are a bad idea

Category: Programming, Ruby

In ruby, there are instance variables and class variables. Class variables may not work the way you think…
So to define a class variable we do the following:

class A
  @@class_variable = "bob"
  def self.get
    @@class_variable
  end
end
class B
  @@class_variable = "sally"
  def self.get
    @@class_variable
  end
end
 
#"bob"
A.get
#"sally"
B.get

Here is the problem. Suppose A is a base class of B:

class A
  @@class_variable = "bob"
  def self.get
    @@class_variable
  end
end
class B < A
  @@class_variable = "sally"
  def self.get
    @@class_variable
  end
end
 
#"sally" !!
A.get
#"sally"
B.get

Basically the problem is that, unlike many other languages, the class variable is not tied to a specific class, but rather once defined at any level of the inheritance hierarchy, it is defined across all child classes.

Fortunately there is a solution, class level instance variables. Every class in ruby is actually a single object of type Class. This object can have an instance variable as follows:

class A
  @class_instance_variable = "bob"
  def self.get
    @class_instance_variable
  end
end
class B < A
  @class_instance_variable = "sally"
  def self.get
    @class_instance_variable
  end
end
 
#"bob"
A.get
#"sally"
B.get
Comments are off for this post

Comments are closed.