2014-05-12 53 views
0

我觀看了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" }, 
      #     ^

任何建議嗎?

+1

,如果你想擺脫Proc.new你既可以使用lambda(stabby lambda語法:' - > {放「goodbye」}')或者使用proc方法'proc {puts「goodbye」}' –

回答

3

使用lambda語法

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" 

使用新的Hash語法可以進一步縮短這個:

def process(input) 
    { 
    q: ->{ puts "Goodbye" }, 
    tweet: ->{ puts "tweeting" }, 
    dm: ->{ puts "direct messaging"}, 
    help: ->{ puts "helping"} 
    }[input.to_sym].call 
end 

process "tweet" 
+1

'lambda'和'proc'不一樣。 –

+0

@PhilidorGreen正確,但它們在本用例中服務於相同的目的 - 「避免使用if語句」 –

+0

很好,不知道這個lambda語法 – peter

1

我不知道是否你建議或者我會建議在這裏提高的優雅或受到質疑的代碼的可讀性,但你可以通過使用哈希存取模式,如進一步縮短:

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"} 
    }[input.to_sym].call 
end 
2

使用Kernel#proc

等同於Proc.new

def process(input) 
    commands = { 
    :q => proc { puts "Goodbye" }, 
    :tweet => proc { puts "tweeting" }, 
    :dm => proc { puts "direct messaging"}, 
    :help => proc { puts "helping"} 
    }[input.to_sym].call 
end