我观看了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”}' –