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?
Use class_name dot variable_name to access a class variable from a class method in Python. Use instance to access variables outside the class.
If you want to use that variable even outside the class, you must declared that variable as a global. Then the variable can be accessed using its name inside and outside the class and not using the instance of the class. class Geek: # Variable defined inside the class.
Use the member-access operator ( . ) between the object variable name and the member name. If the member is Shared, you do not need a variable to access it.
Class methods cannot access instance variables or instance methods directly—they must use an object reference.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With