2012-12-10 34 views
89

試圖創建對象和由紅寶石發送方法傳遞多個參數

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

動態調用方法,其工作正常時

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

但投擲錯誤的參數數目1 2

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

定義的隨機類是

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 

有人可以幫助我如何發送多發參數紅寶石方法動態

回答

169
send("i_take_multiple_arguments", *[25.0,26.0]) #Where star is the "splat" operator 

send(:i_take_multiple_arguments, 25.0, 26.0) 
+17

可能值得注意的是,在這種情況下'*'是「splat」操作符。 –

4

或者,您可以撥打send與它的同義詞__send__

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

順便說一下*你可以pa SS哈希作爲PARAMS逗號隔開,像這樣:

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

或新的哈希語法:

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

據黑,__send__是安全的命名空間。

「發送是一個廣泛的概念:發送電子郵件,數據發送到I/O套接字等等。程序定義一個名爲send的方法與Ruby的內置發送方法衝突並不罕見。因此,Ruby爲您提供了另一種調用send的方法:__send__。按照慣例,沒有人用這個名字寫一個方法,所以內置的Ruby版本總是可用的,並且永遠不會與新編寫的方法發生衝突。這看起來很奇怪,但它比平原從安全的觀點方法名衝突點​​」

黑色也表明在if respond_to?(method_name)包裝調用__send__發送版本。

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.這位基礎良好的Rubyist。曼寧,2009年.P.171。

*我來這裏尋找散列語法__send__,所以可能對其他谷歌有用。 ;)