我如何访问类变量?

时间:2016-09-28 17:01:48

标签: ruby

class TestController < ApplicationController

  def test
    @goodbay = TestClass.varible
  end
end

class TestClass
  @@varible = "var"
end

我收到错误

undefined method 'varible' for TestClass:Class 

@goodbay = TestClass.varible

有什么问题?

3 个答案:

答案 0 :(得分:18)

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

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

p TestClass.variable #=> "var"

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

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

Ruby on Rails专门为类变量提供a convenience method

class TestClass
  mattr_accessor :variable
end

答案 1 :(得分:3)

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

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"

答案 2 :(得分:0)

还有其他方法

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