Vladislav Aniskin
Vladislav Aniskin

Reputation: 349

How do I access class variable?

class TestController < ApplicationController

  def test
    @goodbay = TestClass.varible
  end
end

class TestClass
  @@varible = "var"
end

and i get error

undefined method 'varible' for TestClass:Class 

on the line @goodbay = TestClass.varible

What is wrong?

Upvotes: 28

Views: 57081

Answers (3)

Andrey Deineko
Andrey Deineko

Reputation: 52347

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

class TestClass
  @@varible = "var"

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

TestClass.variable
#=> "var"

Upvotes: 7

zhu jiang
zhu jiang

Reputation: 151

here's another option:

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

Upvotes: 12

Phrogz
Phrogz

Reputation: 303136

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

Upvotes: 35

Related Questions