Ruby send vs __send__

后端 未结 5 1479
长情又很酷
长情又很酷 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 14:06

    If you really need send to behave like it would normally do, you should use __send__, because it won't (it shouldn't) be overriden. Using __send__ is especially useful in metaprogramming, when you don't know what methods the class being manipulated defines. It could have overriden send.

    Watch:

    class Foo
      def bar?
        true
      end
    
      def send(*args)
        false
      end
    end
    
    foo = Foo.new
    foo.send(:bar?)
    # => false
    foo.__send__(:bar?)
    # => true
    

    If you override __send__, Ruby will emit a warning:

    warning: redefining `__send__' may cause serious problems

    Some cases where it would be useful to override send would be where that name is appropriate, like message passing, socket classes, etc.

提交回复
热议问题