ruby respond_to?

今日开发遇到respond_to? 顾详细解析下

参考stackoverflow里面的,做了测试

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?

具体真是这个样子,

respond_to?(p1, p2 = v2) public

Returns true if obj responds to the given method. Private methods are included in the search only if the optional second parameter evaluates to true.

If the method is not implemented, as Process.fork on Windows, File.lchmod on GNU/Linux, etc., false is returned.

If the method is not defined, respond_to_missing? method is called and the result is returned.

Ruby respond_to?

所以,可以写成下面的样子

obj.respond_to?(:protected_method, true)
# true

参考

你可能感兴趣的:(ruby respond_to?)