'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?
Solution 1:[1]
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
Solution 2:[2]
here's another option:
class RubyList
@@geek = "Matz"
@@country = 'USA'
end
RubyList.class_variable_set(:@@geek, 'Matz rocks!')
puts RubyList.class_variable_get(:@@geek)
Solution 3:[3]
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"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Luke W |
Solution 3 |