Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
访问模块';在Ruby中,将类变量放在类中_Ruby_Accessor_Class Variables - Fatal编程技术网

访问模块';在Ruby中,将类变量放在类中

访问模块';在Ruby中,将类变量放在类中,ruby,accessor,class-variables,Ruby,Accessor,Class Variables,我有一个模块,里面有一个类变量 module Abc @@variable = "huhu" def self.get_variable @@variable end class Hello def hola puts Abc.get_variable end end end a = Abc::Hello.new a.hola 不使用get\u variable方法,是否可以在Hello中获取@@variable?我的意思是像Abc

我有一个模块,里面有一个类变量

module Abc
  @@variable = "huhu"

  def self.get_variable
    @@variable
  end

  class Hello
    def hola
      puts Abc.get_variable
    end
  end
end

a = Abc::Hello.new
a.hola

不使用
get\u variable
方法,是否可以在
Hello
中获取
@@variable
?我的意思是像Abc.variable之类的东西会很好。只是好奇。

您不能在模块
Abc
中的
Hello
类的范围内直接访问
@@variable
(即
Abc.variable
)。为什么?因为,当Ruby解释器看到类似于
Abc.variable
的东西时,它会认为
variable
是Abc的类/模块方法

在使用Ruby编程时,考虑Ruby的方式很重要。

试试这个

Abc.class_variable_get(:variable)

旁注:如果你想在很大程度上克服这种想法,我已经在最近举行的Ruby Conf India 2011中分享了我的经验教训。请随时观看我的演讲,并给出您的评分和反馈。最重要的是,请阅读最后一张幻灯片,其中我提到了帮助我形成Ruby思维方式的资源。可能的重复请扩展您的代码或补充说明,否则您的答案可能会被版主删除。