15

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

2 回答 2

12

文档中:

如果 obj 响应给定的方法,则返回 true。仅当可选的第二个参数的计算结果为 true 时,私有和受保护的方法才会包含在搜索中

编写问题时(Ruby 1.8.7):

如果 obj 响应给定的方法,则返回 true。仅当可选的第二个参数的计算结果为 true 时,私有方法才会包含在搜索中。

于 2014-06-25T15:40:15.320 回答
9

是否respond_to?应该寻找受保护的方法正在争论中(检查这个问题

Matz 表示它可能会在 Ruby 2.0 中发生变化。

请注意,某些类可能会使用#method_missing和专门化(或者通过在 Ruby 1.9.2+ 中#respond_to?指定 a 更好),在这种情况下,您将不可靠。#respond_to_missing?obj.methods.include?

于 2010-04-03T00:28:38.920 回答