从模块中访问变量

时间:2013-09-07 03:25:05

标签: ruby oop

尝试从模块中获取模块外部定义的变量

@variable = "variable"

module A
  def write
    puts @variable
  end
end

extend A
write # -> "variable"
# works ok, but i'll be loading a few modules with the same method name "write"
# need to be able to call A.write, A1.write, A2.write and so on

module B
  module_function
  def write
    puts @variable
  end
end

extend B
B.write # ->  
# Can call the B.write
# is returning nothing, not getting @variable

module C
  module_function
  def write var
    puts var
  end
end

extend C
C.write @variable # -> "variable"
# works ok

是我在实践中发现好的解决方案吗?或者有更好的方法吗?不确定调用module_function,因为我在阅读定义后仍然没有得到它,不确定它还在做什么

0 个答案:

没有答案