如何从Ruby模块中仅导入几个函数?

假设我有一个带有方法的模块:function1,function2,function3。 我想导入function1和function2但不导入function3。 有没有办法在ruby中做到这一点?

不确定是否有一种干净的方法来添加所需的方法,但您可以使用undef_method删除不需要的方法。

 module Foo def function1 end def function2 end def function3 end end module MiniFoo include Foo not_wanted_methods = Foo.instance_methods - %w(function1 function2) not_wanted_methods.each {|m| undef_method m} end class Whatever include MiniFoo end 

类似的解决方案,但更自动。 我不知道会发生什么样的奇怪事情。

 module Foo def m1 puts "Hello from m1" end def m2 puts "Hllo from m2" end end class Module alias :__include__ :include def include(mod, *methods) if methods.size > 0 tmp = mod.dup new_mod = Object.const_set("Mod#{tmp.object_id}", tmp) toremove = new_mod.instance_methods.reject { |m| methods.include? m.to_sym } toremove.each { |m| new_mod.send(:undef_method, m) } __include__(new_mod) else __include__(mod) end end end class Bar include Foo end class Baz include Foo, :m2 end bar = Bar.new baz = Baz.new p bar.methods - Object.methods p baz.methods - Object.methods => ["m1", "m2"] ["m2"] 

假设您控制模块的源代码,我认为最干净的方法是将模块拆分为更多,呃,模块化的部分。

如果你只想要一个模块的某些部分,这是一个非常好的迹象,你可以将该模块重构为多个负责较少的模块。