2016-10-31 18 views
0

說我有一個方法,它接受一個字符串和一個選項散列。選項散列具有方法名稱作爲鍵,布爾值/值作爲值。發送方法:選擇何時傳遞參數

some_method("foo", upcase: true, times: 5) 

什麼這種方法應該做的是把字符串,並運行基於選項哈希字符串某些方法,在這種情況下,就應該使串upcase,那麼多它通過5.我們得到FOOFOOFOOFOOFOO作爲輸出。

我遇到的問題是,當我使用send方法,一些從options哈希方法需要參數(如*,有的沒有(如「upcase」)。

這裏我有這麼遠。

def method(string, options = {}) 
    options.each do |method_name, arg| 
    method_name = :* if method_name == :times 
    mod_string = mod_string.send(method_name, arg) 
    end 
end 

我得到預期

錯誤的參數數目錯誤(1給出,預計0)

(REPL):9:`upcase」

所以,我的問題是:有沒有辦法時,有一種說法是隻發送的說法?

我想出的唯一事情是使用if語句來檢查布爾值

options.each do |method_name, arg| 
    method_name = :* if method_name == :times 
    if arg == true 
     mod_string = mod_string.send(method_name) 
    elsif !(!!arg == arg) 
     mod_string = mod_string.send(method_name, arg) 
    end 
    end 

我只是想看看有沒有更好的辦法。

回答

1

「當一個方法有一個必需的參數,把它稱爲」:

method = mod_string.method(method_name) 
arity = method.arity 
case arity 
when 1, -1 
    method.call(arg) 
when 0 
    method.call 
else 
    raise "Method requires #{arity} arguments" 
end 

一個可能是更好的方法是調整你的哈希值,並給它正是你想傳遞一個數組參數:

some_method("foo", upcase: [], times: [5]) 

那麼你可以簡單地mod_string.send(method_name, *arg)

+0

我剛剛做了'arg = [arg] .reject {| el | el == true || el == false}'和'mod_string.send(method_name,arg)'。它工作得很好。謝謝 – davidhu2000