与Ruby相反的是什么?

QAZ*_*QAZ 16 ruby reflection

如果我有一个类实例,包含几个包含的模块,我可以动态取消包含一个特定的模块(为了替换它)?

谢谢.

Jus*_*iss 6

这不是真正的同样的事情,但你可以伪造它是这样的:

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)操作.


Jör*_*tag 5

不可以.你不能在Ruby 语言中包含mixin .在某些Ruby 实现中,您可以通过在C或Java中编写特定于实现的扩展(或者在Rubinius的情况下甚至是Ruby)来实现.


eli*_*iah 4

尝试http://github.com/yrashk/rbmodexcl,它unextend为您提供了一种方法。