我如何访问类变量?

Vla*_*kin 15 ruby

class TestController < ApplicationController

  def test
    @goodbay = TestClass.varible
  end
end

class TestClass
  @@varible = "var"
end
Run Code Online (Sandbox Code Playgroud)

我得到错误

undefined method 'varible' for TestClass:Class 
Run Code Online (Sandbox Code Playgroud)

在线上 @goodbay = TestClass.varible

怎么了?

Phr*_*ogz 23

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

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

p TestClass.variable #=> "var"
Run Code Online (Sandbox Code Playgroud)

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

class TestClass
  @variable = "var"
  class << self
    attr_accessor :variable
  end
end
Run Code Online (Sandbox Code Playgroud)

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

class TestClass
  mattr_accessor :variable
end
Run Code Online (Sandbox Code Playgroud)

  • 另外作为一个注释,这不需要一个访问器方法,因为`Object#instance_variable_get`将允许访问所有实例变量(`@`)和`Object#class_variable_get`为类变量(`@@`)提供相同的功能而不需要对于显式的getter方法,例如`TestClass.instance_variable_get(:@ variable)`或`TestClass.class_variable_get(:@@ variable)` (6认同)
  • 重新访问实例/类变量(主要从控制台),对我来说它的工作方式类似于 `FooClass.class_variable_set(:@@foo, 'bar')` 和 `FooClass.class_variable_get(:@@foo)`,对于实例 ` foo_class.instance_variable_set(:@foo, 'baz')` 和 `foo_class.instance_variable_get(:@foo)`。它们接受符号 `:@foo` 或字符串 `'@foo'`。(感谢@engineersmnky 发帖。) (4认同)

小智 9

这是另一个选择:

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


And*_*eko 5

您必须正确访问类变量。其中一种方式如下:

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"
Run Code Online (Sandbox Code Playgroud)