【问题标题】:How to access class variables in included ruby modules?如何访问包含的 ruby​​ 模块中的类变量?
【发布时间】:2012-01-06 05:41:04
【问题描述】:

我需要知道包含的 ruby​​ 模块是否可以访问类变量。让我们说:

require 'bar'

class Foo

 @i_am_important

  Bar.do_stuff

end

Module Bar
  def Bar.do_stuff
    @i_am_important.stuff...
  end
end

有没有办法使上述工作?

编辑:改进的示例, edit2:解决问题

我只是改变了我的方法:Bar 变成了自己的一个类,并在初始化时传递了“i_am_important”。可能不是最好的解决方案,但最终有效。谢谢你的帮助。

【问题讨论】:

  • 首先,如果要包含模块,则必须将所有可用于托管类的方法设为实例方法

标签: ruby variables module


【解决方案1】:

您可以在类中包含模块以获取访问权限,例如

    module MyModule
    @@my_val = 4
    end

    class MyClass
    include MyModule
    value = @@my_val
    end

【讨论】:

  • 感谢您的回答,但对于我的场景,我需要 MyClass 中的 @my_val。谁可以 MyModule 访问它?
  • @@my_val 不是全局变量,而是类实例变量
  • 我刚刚编辑了我的示例。我希望现在可以更清楚地看到我的问题。
【解决方案2】:

为什么要跨类和模块的门使用变量?我认为有这样的方式:

module Bar
  def do_stuff
    puts im_am_important
  end
end

class Foo
  include Bar

  def im_am_important
    100
  end
end

Foo.new.do_stuff  # => 100

【讨论】:

    【解决方案3】:

    怎么样:

    #foo.rb
    
    @var
    module My_foo 
      var = @var
      def My_foo.my_method(var)
        puts(var)
      end
    end
    

    #bar.rb
    require 'foo'
    
    class Bar
      extend My_foo
      @important_var = "bla"
      My_foo.my_method(@important_var)
    end
    

    ruby bar.rb => 布拉

    【讨论】:

    • 谢谢,但我忘了说 Foo 已经扩展了另一个类。毕竟这就是我尝试使用模块的原因。
    猜你喜欢
    • 1970-01-01
    • 2011-10-13
    • 2015-09-11
    • 2015-05-25
    • 1970-01-01
    • 2011-03-30
    • 2011-02-20
    • 2016-11-24
    • 2015-02-10
    相关资源
    最近更新 更多