Ruby Language Metaprogramming send() methodsend() is used to pass message to object . send() is an instance method of the Object class. The first argument in send() is the message that you're sending to the object - that is, the name of a method. It could be string or symbol but symbols are preferred.
In the code you posted, *args simply indicates that the method accepts a variable number of arguments in an array called args . It could have been called anything you want (following the Ruby naming rules, of course).
In ruby, arguments inside a method are passed by reference In ruby, we have a different situation, the variable that we have inside the method stores a reference to an object. Thus, if we will change an object inside the method, then it will be changed also outside the method.
send("i_take_multiple_arguments", *[25.0,26.0]) #Where star is the "splat" operator
or
send(:i_take_multiple_arguments, 25.0, 26.0)
You can alternately call send
with it's synonym __send__
:
r = RandomClass.new
r.__send__(:i_take_multiple_arguments, 'a_param', 'b_param')
By the way* you can pass hashes as params comma separated like so:
imaginary_object.__send__(:find, :city => "city100")
or new hash syntax:
imaginary_object.__send__(:find, city: "city100", loc: [-76, 39])
According to Black, __send__
is safer to namespace.
“Sending is a broad concept: email is sent, data gets sent to I/O sockets, and so forth. It’s not uncommon for programs to define a method called send that conflicts with Ruby’s built-in send method. Therefore, Ruby gives you an alternative way to call send:
__send__
. By convention, no one ever writes a method with that name, so the built-in Ruby version is always available and never comes into conflict with newly written methods. It looks strange, but it’s safer than the plain send version from the point of view of method-name clashes”
Black also suggests wrapping calls to __send__
in if respond_to?(method_name)
.
if r.respond_to?(method_name)
puts r.__send__(method_name)
else
puts "#{r.to_s} doesn't respond to #{method_name}"
end
Ref: Black, David A. The well-grounded Rubyist. Manning, 2009. P.171.
*I came here looking for hash syntax for __send__
, so may be useful for other googlers. ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With