美文网首页
ruby respond_to?

ruby respond_to?

作者: AQ王浩 | 来源:发表于2014-06-26 00:23 被阅读148次

    今日开发遇到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?

          本文链接:https://www.haomeiwen.com/subject/krjjtttx.html