gpt4 book ai didi

ruby - 什么时候用undef_method,什么时候用remove_method?

转载 作者:数据小太阳 更新时间:2023-10-29 06:35:35 26 4
gpt4 key购买 nike

我想重新定义一个方法,但要避免与之相关的警告。我应该使用 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 将方法 m 添加到类中,remove_method :m 删除 m。但是,如果父类(super class)有一个 m 方法,那么它仍然会被使用。

undef_method,OTOH,更像这样:

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

所以 undef_method 实际上并没有删除该方法,它用一个特殊的内部标志替换了该方法,如果您尝试调用该方法,该标志会导致 Ruby 报错。

听起来您正在尝试替换现有方法,replace 在语义上与 remove 后跟 add 相同,所以 remove_method 可能更合适。但是,如果您想偏执并确保替换方法到位,那么 undef_method 会很有用;或者,如果出于某种原因您需要在一个地方删除该方法并将其添加到另一个地方,undef_method 至少会告诉您您只完成了一半的工作,而 remove_method要么留下父类(super class)的实现(以及可能的奇怪错误),要么留下一个相当困惑的 NoMethodError

关于ruby - 什么时候用undef_method,什么时候用remove_method?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11894308/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com