Why does Ruby have two send and __send__methods?

Asked

Viewed 105 times

4

Ruby objects have a method called send that we can call methods dynamically.

class MyClass
  private
  def true_method?
    true
  end
end

Example:

mc = MyClass.new
mc.send(:true_method?)
mc.__send__(:true_method?)

Why do you have these two methods?

  • 1

    I think you have a similar question at the international forum, see if it helps you: https://stackoverflow.com/questions/4658269/ruby-send-vs-send

1 answer

8


Given that dynamic modifications such as method superscripts are common to see in Ruby, the Object#__send__ and Object#send is a way to protect objects against overwriting. The __send__ serves as an internal alias, which you can use if your object has some resetting of send. For example:

"hello world".send :upcase
=> "HELLO WORLD"

module EvilSend
  def send(foo)
    "Não foi dessa vez..."
  end
end

String.include EvilSend
"hello world".send :upcase
=> "Não foi dessa vez"

"hello world".__send__ :upcase
=> "HELLO WORLD"

Note that there is no Ruby Warning on the superscript of this method. That’s why there is __send__. The method that CANNOT be overwritten under any circumstances is the __send__. If you try, Ruby throws a warning.

Warning: Redefining '__send__' may Serious problems

  • I also found that one should use the send when you implement send in your class. For example: In your Usernotification class you have a send method, for you user the Object send you use the send

  • I believe that this behavior is tied to the question of open classes, it makes sense?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.