Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access class variable?

Tags:

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?

like image 578
Vladislav Aniskin Avatar asked Sep 28 '16 17:09

Vladislav Aniskin


People also ask

How do you access class variables in Python?

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.

How can you access class 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.

How do you access the variable of an object?

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.

Can we access class variables using object?

Class methods cannot access instance variables or instance methods directly—they must use an object reference.


1 Answers

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 
like image 148
Phrogz Avatar answered Sep 21 '22 16:09

Phrogz