ruby – 何时使用undef_method,何时使用remove_method?

我想重新定义一个方法,但是避免与之相关联的警告.我应该使用undef_method还是remove_method这样做?

(是的,重新定义方法有点恶作剧,我这样做是因为在运行单元测试时我想要使用一些记忆,而不是运行程序时).

解决方法

fine manual

undef_method(symbol) → self

Prevents the current class from responding to calls to the named method. Contrast this with remove_method,which deletes the method from the particular class; Ruby will still search superclasses and mixed-in modules for a possible receiver.

所以这样一个remove_method:

class CC < C
    remove_method :m
end

基本上与此相反:

class CC < C
    def m
    end
end

其中,def将方法m添加到类中,remove_method:m删除m.但是,如果超类有一个m方法,那么仍然会被使用.

undef_method,OTOH,更像是这样:

class CC < C
    def m
        raise 'No,you cannot do that.'
    end
end

所以undef_method实际上并没有删除方法,它会使用一个特殊的内部标志替换该方法,如果您尝试调用方法,则会引起Ruby的抱怨.

听起来你正在尝试替换一个现有的方法,而替换在语义上与删除相同,后跟一个add,因此remove_method可能更合适.然而,如果你想要偏执,并确保替换方法到位,那么undef_method将是有用的;或者,如果由于某种原因,您需要在一个地方删除方法并将其添加到另一个位置,则undef_method至少会告诉您,您只做了一半的工作,而remove_method会让您离开超级类的实现(和可能的奇怪的错误)或者一个比较混乱的NoMethodError.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...