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:
Since dynamic modifications such as method overrides are a common sight in Ruby,Object#__send__
and Object#send
is a way to protect objects from being overwritten. __send__
serves as an internal alias, which you can use if your object has any send
redefinitions. 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 warning from Ruby about overriding this method. That's why there is __send__
. The method that CANNOT be overridden under any circumstances is __send__
. If you try, Ruby throws a warning .
warning: redefining '
__send__
' may cause serious problems