3

是否可以在 Ruby 中重新打开匿名模块?以下不起作用:

m = Module.new
module m
end

“SyntaxError: (eval):2: class/module name must be CONSTANT”。

4

1 回答 1

6

是的。但是你必须使用一个常数。

M = Module.new
module M
end

你也可以这样做M = m


另一种方式:

m = Module.new do
  def self.foo1
    1
  end
end

m.class_eval do
  def self.foo2
    2
  end
end

m.foo1 + m.foo2  #=> 3
于 2012-07-29T11:22:55.263 回答