0

试图从模块内部获取模块外部定义的变量

@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 因为我在阅读定义后仍然没有得到它,不知道它还在做什么

4

0 回答 0