直接访问受保护方法和使用send之间的区别

Kir*_*lly 4 ruby class

为什么以下代码中的两种类型的调用方法之间存在差异:

class Access
    def method_missing name
        print "Method is missing"
    end

    protected
    def protected_method
        print "Calling Protected Method"
    end
end

access = Access.new
access.protected_method #Method is missing
access.send(:protected_method) #Calling Protected Method
Run Code Online (Sandbox Code Playgroud)

access.protected_method按预期工作.但该send选项尝试调用该方法,即使它受到保护.我想知道内部发生了什么.

我得到一个要调用的方法的字符串,所以我想使用,send但我不想调用受保护的方法.

Jör*_*tag 6

这就是send有效的方式.使用public_send替代,如果你只是想调用公共方法.