怎么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