我觀看了https://gorails.com/blog/refactoring-if-statements的視頻,但正在尋找一種更簡潔的方式來避免使用多個if或case語句。 以下工作迴避使用if語句:縮短代碼
def process(input)
commands = {
:q => Proc.new { puts "Goodbye" },
:tweet => Proc.new { puts "tweeting" },
:dm => Proc.new { puts "direct messaging"},
:help => Proc.new { puts "helping"}
}
commands[input.to_sym].call
end
process "tweet"
但我怎麼能進一步縮短呢?我嘗試以下
def process(input)
commands = {
:q => { puts "Goodbye" },
:tweet => { puts "tweeting" },
:dm => { puts "direct messaging"},
:help => { puts "helping"}
}
commands[input.to_sym].to_proc.call
end
process "tweet"
但後來我得到的錯誤
# syntax error, unexpected tSTRING_BEG, expecting keyword_do or '{' or '('
# :q => { puts "Goodbye" },
# ^
任何建議嗎?
,如果你想擺脫Proc.new你既可以使用lambda(stabby lambda語法:' - > {放「goodbye」}')或者使用proc方法'proc {puts「goodbye」}' –