响应?和受保护的方法
怎么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
It may not be so obvious how respond_to? works in ruby.
Consider that:
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?
So if 'obj' responds to protected_method we should expect
obj.protected_method
not to raise an exception, shouldn't we?
...but it raises obviously
Documentation points that calling respond_to? with 2nd argument set to true check private method as well
obj.respond_to?(:private_method, true)
# true
And that's far more reasonable
So the question is how to check if object responds to public method only?
Is there a solution better than that?
obj.methods.include?(:public_method)
# true
obj.methods.include?(:protected_method)
# false
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自文档:
当问题被写入时(Ruby 1.8.7):
From the documentation:
When the question was written (Ruby 1.8.7):
目前正在争论
respond_to?
是否应该查找受保护的方法(检查 这个问题)Matz 表示它可能会在 Ruby 2.0 中改变。
请注意,某些类可能使用
#method_missing
并专门化#respond_to?
(或者在 Ruby 1.9.2+ 中指定#respond_to_missing?
更好),在这种情况下,您的 obj.methods.include? 将不可靠。It is under debate if
respond_to?
should look for protected methods or not (check this issue)Matz has stated that it will probably change in Ruby 2.0.
Note some classes might use
#method_missing
and specialize#respond_to?
(or better by specify a#respond_to_missing?
in Ruby 1.9.2+), in which case yourobj.methods.include?
will not be reliable.