response_to可能并不那么明显?以红宝石工作。 考虑以下因素:respond_to?和受保护的方法
class A
def public_method
end
protected
def protected_method
end
private
def private_method
end
end
obj = A.new
obj.respond_to?(:public_method)
# true - that's pretty obvious
obj.respond_to?(:private_method)
# false - as expected
obj.respond_to?(:protected_method)
# true - WTF?
所以,如果 'OBJ' 响应protected_method我们应该期待
obj.protected_method
没有引发异常,不是吗?
...但它明显提高
调用respond_to的文档点?与第二个参数设置为true检查私有方法以及
obj.respond_to?(:private_method, true)
# true
而这更为合理
所以,问题是如何检查对象只响应公众的方法? 有没有比这更好的解决方案?
obj.methods.include?(:public_method)
# true
obj.methods.include?(:protected_method)
# false
我很难理解翻译日语,但无论如何,很高兴知道红宝石核心考虑这个问题。至少有一个可以使用obj.class.public_method_defined?(:protected_method),它的工作方式与预期的一样,但不会处理单例方法,所以我认为这是一种解决方法,而不是真正的解决方案 – mlomnicki 2010-04-03 01:24:13
回答更新信息 – 2011-11-24 21:55:10