如何访问包含的ruby模块中的类变量?

时间:2011-11-25 10:10:50

标签: ruby variables module

我需要知道包含的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”。可能不是最好的解决方案,但最后工作。谢谢你的帮助。

3 个答案:

答案 0 :(得分:0)

您可以在类中包含模块以获取

之类的访问权限
    module MyModule
    @@my_val = 4
    end

    class MyClass
    include MyModule
    value = @@my_val
    end

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

怎么样:

#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 => BLA

相关问题