How do I access class variable?

here's another option:

class RubyList
  @@geek = "Matz"
  @@country = 'USA'
end
RubyList.class_variable_set(:@@geek, 'Matz rocks!')
puts RubyList.class_variable_get(:@@geek)

In Ruby, reading and writing to @instance variables (and @@class variables) of an object must be done through a method on that object. For example:

class TestClass
  @@variable = "var"
  def self.variable
    # Return the value of this variable
    @@variable
  end
end

p TestClass.variable #=> "var"

Ruby has some built-in methods to create simple accessor methods for you. If you will use an instance variable on the class (instead of a class variable):

class TestClass
  @variable = "var"
  class << self
    attr_accessor :variable
  end
end

Ruby on Rails offers a convenience method specifically for class variables:

class TestClass
  mattr_accessor :variable
end

You have to access the class variable correctly. One of the ways is as follows:

class TestClass
  @@varible = "var"

  class << self
    def variable
      @@varible
    end
  end

 # above is the same as
 # def self.variable
 #   @@variable
 # end
end

TestClass.variable
#=> "var"

Tags:

Ruby