A ruby ​​send method that passes multiple parameters

Attempting to create objects and dynamic method calls

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

which works fine when

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

but the erroneous number of arguments is 1 for 2 for

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

Defined random class

 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 dynamically send parameters to the ruby ​​method

+85
ruby
Dec 10 '12 at 5:40
source share
2 answers
 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) 
+165
Dec 10
source share

You can alternately call send with it the synonym __send__ :

 r = RandomClass.new r.__send__(:i_take_multiple_arguments, 'a_param', 'b_param') 

By the way * you can pass hashes as params, separated by commas:

 imaginary_object.__send__(:find, :city => "city100") 

or the new hash syntax:

 imaginary_object.__send__(:find, city: "city100", loc: [-76, 39]) 

According to Black, __send__ safer for the namespace.

"Sending is a broad concept: an email is sent, data is sent to I / O sockets, etc. Often, for programs to define a method called send, which conflicts with Rubys' built-in send method, 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 version of Ruby is always available and never conflicts with newly written methods., but it is safer than a simple version of sending in terms of name conflicts methods "

Black also suggests wrapping __send__ calls 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. Well-grounded rubist. Manning, 2009.S.171.

* I came here to find the hash syntax for __send__ , so it can be useful to other googlers.;)

+4
Jun 16 '17 at 17:10
source share



All Articles