开发者

Access a module's class variables inside a class in Ruby

开发者 https://www.devze.com 2023-03-23 14:46 出处:网络
I have a module with a class variable in it module Abc @@variable = \"huhu\" def self.get_variable @@variable

I have a module with a class variable in it

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

Is it possible to get @@variable inside Hello without using get_variable method? I 开发者_高级运维mean something like Abc.variable would be nice. Just curious.


You cannot access @@variable directly (i.e., Abc.variable) within the scope of the Hello class in the module Abc. Why? Because, when the Ruby interpreter sees something like Abc.variable, it would think variable as class/module method of Abc.

It is important to think the Ruby way when programming in Ruby.


try this

Abc.class_variable_get(:variable)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号