Search code examples
rubylanguage-designclass-variables

why there are class variables in ruby?


If creating a class variable is often dangerous and unpredictable why do we need them? If solution is just to use class instance variable with the class level accessors:

class Foo
  @variable = :something

  def self.getvariable
    @variable
  end

  def self.setvariable(value)
    @variable = value
  end
end

Then why do we need class variables???


Solution

  • Class variables have their use on occasion, but I agree that using the eigenclass is frequently more useful:

    class Foo
      @bar = 'bar'
      class << self
        attr_accessor :bar
      end
    end
    
    puts Foo.bar         # bar
    puts Foo.bar = 'baz' # baz
    

    The above is safe with inheritance, because it sets a variable in the Foo constant, rather than a class variable.

    Foo.new.instance_eval { puts @@bar } # error