Ruby send vs __send__

后端 未结 5 1482
长情又很酷
长情又很酷 2020-12-12 13:36

I understand the concept of some_instance.send but I\'m trying to figure out why you can call this both ways. The Ruby Koans imply that there is some reason bey

5条回答
  •  既然无缘
    2020-12-12 13:55

    Apart from what others already told you, and what boils down to saying that send and __send__ are two aliases of the same method, you might be interested in the third, somwhat different possibility, which is public_send. Example:

    A, B, C = Module.new, Module.new, Module.new
    B.include A #=> error -- private method
    B.send :include, A #=> bypasses the method's privacy
    C.public_send :include, A #=> does not bypass privacy
    

    Update: Since Ruby 2.1, Module#include and Module#extend methods become public, so the above example would not work anymore.

提交回复
热议问题