这不是真正的同样的事情,但你可以伪造它是这样的:
module A
def hello
puts "hi!"
end
end
class B
include A
end
class C
include A
end
B.new.hello # prints "Hi!"
class Module
def uninclude(mod)
mod.instance_methods.each do |method|
undef_method(method)
end
end
end
class B
uninclude A
end
B.new.hello rescue puts "Undefined!" # prints "Undefined!"
C.new.hello # prints "Hi!"
Run Code Online (Sandbox Code Playgroud)
这可能适用于常见情况,但它可能会在更复杂的情况下咬你,比如模块将自身插入到继承链中,或者你有其他模块提供的命名方法与你仍然希望能够调用的方法相同.您还需要手动撤消任何Module.included?(klass)操作.
不可以.你不能在Ruby 语言中包含mixin .在某些Ruby 实现中,您可以通过在C或Java中编写特定于实现的扩展(或者在Rubinius的情况下甚至是Ruby)来实现.