ruby send method passing multiple parameters

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. ;)


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)

Tags:

Ruby