ruby send method passing multiple parameters

Ruby

Ruby Problem Overview


Trying to create objects and call methods dynamically by

Object.const_get(class_name).new.send(method_name,parameters_array)

which is working fine when

Object.const_get(RandomClass).new.send(i_take_arguments,[10.0])

but throwing wrong number of arguments 1 for 2 for

Object.const_get(RandomClass).new.send(i_take_multiple_arguments,[25.0,26.0])

The Random Class defined is

class RandomClass
def i_am_method_one
	puts "I am method 1"
end
def i_take_arguments(a)
	puts "the argument passed is #{a}"
end
def i_take_multiple_arguments(b,c)
	puts "the arguments passed are #{b} and #{c}"
end
    end

Can someone help me on how to send mutiple parameters to a ruby method dynamically

Ruby Solutions


Solution 1 - Ruby

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)

Solution 2 - Ruby

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionrails4sandeepView Question on Stackoverflow
Solution 1 - Rubyuser904990View Answer on Stackoverflow
Solution 2 - RubyTony CroninView Answer on Stackoverflow