Why does Ruby have two send and __send__ methods?

3

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?

    
asked by anonymous 27.11.2018 / 18:42

1 answer

7

Given that dynamic modifications such as method overrides are commonplace in Ruby, Object#__send__ and Object#send is a way to protect objects against overwriting. __send__ serves as an internal alias, which you can use if your object has some redefinition 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"

Notice that there is no Ruby warning about overwriting this method. So there is __send__ . The method that can NOT be overwritten, under any circumstances, is __send__ . If you try, Ruby launches a warning .

  

warning: redefining ' __send__ ' may cause serious problems

    
27.11.2018 / 22:44