【问题标题】:Alternative to if-then-else or case statements替代 if-then-else 或 case 语句
【发布时间】:2019-01-11 15:04:54
【问题描述】:

我正在从字符串中解析关键字,并想知道除了大量 if-then-else 语句或使用 switch 语句之外是否还有其他方法。任何方向都会有所帮助

application = application.downcase
if(application.include?("ssl"))
     return "SSL"
elsif(application.include?("ssh"))
     return "SSH"
elsif(application.include?("dce"))
     return "DCE"
elsif(application.include?("https"))
     return "HTTPS"
elsif(application.include?("http"))
     return "http"
else
     return "nil"

【问题讨论】:

  • application.include?("https") 的情况下返回什么?
  • 检查它是否在一个数组中,大写它,特殊情况的http。然后找出它为什么不同,并让它变得不必如此。

标签: ruby string if-statement search


【解决方案1】:

这是一种方式

def your_method(application)
  application = application.downcase
  %w(ssl ssh dce https).each do |p|
    return p.upcase if application.include?(p)
  end
  application.include?("http") ? "http" : "nil"
end

【讨论】:

    【解决方案2】:

    这是一个稍微短一点的方式

    %w[SSL SSH DCE HTTPS http].each do |p|
      return p if application =~ /#{p}/i
    end
    "nil"
    

    这可能是最短的

    %w[SSL SSH DCE HTTPS http].find { |p| application =~ /#{p}/i } || "nil"
    

    除非您选择较短的变量名

    app.upcase[/SSL|SSH|DCE|HTTPS/] || (app =~ /http/i ? "http" : "nil")
    

    【讨论】: