Ruby 动态编程与相关技术全解析
1. 方法移除与未定义处理
在 Ruby 中,当一个类的祖先类定义了同名方法时,祖先类的方法不会被移除。以下是一个示例代码:
class Y
def somemethod
puts("Y's somemethod")
end
end
class Z < Y
def somemethod
puts("Z's somemethod")
end
end
zob = Z.new
zob.somemethod #=> Z's somemethod
class Z
remove_method( :somemethod ) # Remove somemethod from Z class
end
zob.somemethod #=> Y's somemethod
在这个例子中, somemethod 从 Z 类中被移除,当调用 zob.somemethod 时,Ruby 会执行 Z 类祖先类中同名的第一个方法,这里 Y 是 Z 的祖先类,所以调用了 Y 的 somemethod 方法。
与之相对的是 undef_method
超级会员免费看
订阅专栏 解锁全文
1073

被折叠的 条评论
为什么被折叠?



