ruby 如何访问类变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39753594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:51:38  来源:igfitidea点击:

How do I access class variable?

ruby

提问by Vladislav Aniskin

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

在线上 @goodbay = TestClass.varible

What is wrong?

怎么了?

回答by Phrogz

In Ruby, reading and writing to @instancevariables (and @@classvariables) of an object must be done through a method on that object. For example:

在 Ruby 中,必须通过该对象上的方法来读取和写入对象的@instance变量(和@@class变量)。例如:

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):

Ruby 有一些内置方法可以为您创建简单的访问器方法。如果您将在类上使用实例变量(而不是类变量):

class TestClass
  @variable = "var"
  class << self
    attr_accessor :variable
  end
end

Ruby on Rails offers a convenience methodspecifically for class variables:

Ruby on Rails 提供了一种专门用于类变量的便捷方法

class TestClass
  mattr_accessor :variable
end

回答by Andrey Deineko

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"

回答by zhu jiang

hava other method

有其他方法

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