How to access a class variable?

class TestController < ApplicationController

  def test
    @goodbay = TestClass.varible
  end
end

class TestClass
  @@varible = "var"
end

and i get an error

undefined method 'varible' for TestClass:Class 

on the line @goodbay = TestClass.varible

What's wrong?

+12
source share
2 answers

In Ruby, reading and writing to the variables @instance(and @@classvariables) of an object must be done using the method on that object. For instance:

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

p TestClass.variable #=> "var"

Ruby has built-in methods for creating simple access methods. If you use a class instance variable (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
+16
source

You must correctly access the class instance variable. One way 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"
+3
source

Source: https://habr.com/ru/post/1656124/


All Articles