2010-03-29 42 views
14

我目前被困在這個問題上。我已經在我創建的類中掛上了method_missing函數。當一個不存在的函數被調用時,我想調用另一個我知道存在的函數,將args數組作爲所有參數傳遞給第二個函數。有沒有人知道一種方法來做到這一點?例如,我想要做這樣的事情:Ruby - 將數組的值作爲每個參數傳遞給調用方法

class Blah 
    def valid_method(p1, p2, p3, opt=false) 
     puts "p1: #{p1}, p2: #{p2}, p3: #{p3}, opt: #{opt.inspect}" 
    end 

    def method_missing(methodname, *args) 
     if methodname.to_s =~ /_with_opt$/ 
      real_method = methodname.to_s.gsub(/_with_opt$/, '') 
      send(real_method, args) # <-- this is the problem 
     end 
    end 
end 

b = Blah.new 
b.valid_method(1,2,3)   # output: p1: 1, p2: 2, p3: 3, opt: false 
b.valid_method_with_opt(2,3,4) # output: p1: 2, p2: 3, p3: 4, opt: true 

(哦,順便說一句和,上面的例子不工作對我來說)

編輯

這是這樣的作品,根據所提供的答案代碼(有代碼錯誤以上):

class Blah 
    def valid_method(p1, p2, p3, opt=false) 
     puts "p1: #{p1}, p2: #{p2}, p3: #{p3}, opt: #{opt.inspect}" 
    end 

    def method_missing(methodname, *args) 
     if methodname.to_s =~ /_with_opt$/ 
      real_method = methodname.to_s.gsub(/_with_opt$/, '') 
      args << true 
      send(real_method, *args) # <-- this is the problem 
     end 
    end 
end 

b = Blah.new 
b.valid_method(1,2,3)   # output: p1: 1, p2: 2, p3: 3, opt: false 
b.valid_method_with_opt(2,3,4) # output: p1: 2, p2: 3, p3: 4, opt: true 

回答

25

圖示的args陣列:send(real_method, *args)

相關問題