Ruby send vs __send__

Some classes (for example the standard library's socket class) define their own send method which has nothing to do with Object#send. So if you want to work with objects of any class, you need to use __send__ to be on the safe side.

Now that leaves the question, why there is send and not just __send__. If there were only __send__ the name send could be used by other classes without any confusion. The reason for that is that send existed first and only later it was realized that the name send might also usefully be used in other contexts, so __send__ was added (that's the same thing that happened with id and object_id by the way).


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.

Tags:

Ruby

Syntax