Question :
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?
Answer :
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