【问题标题】:Condense several conditional statement comparing the same value压缩几个比较相同值的条件语句
【发布时间】:2018-04-22 11:34:19
【问题描述】:

想知道有没有办法压缩这行代码:

elsif i == '+' || i == '-' || i == '/' || i == '*'

【问题讨论】:

    标签: ruby if-statement conditional


    【解决方案1】:

    case when 控制结构允许这样的压缩线:

    case i
    when '+', '-', '/', '*'  # <= condensed line of code
      puts "operator!"
    end
    

    【讨论】:

    • ...或when /[-+\/*]/
    【解决方案2】:

    你可以这样做

    "+-/*".include?(i)
    

    【讨论】:

    • 啊,谢谢。我最初只是制作了一个单独的数组,并将其作为临时解决方案进行了比较。这很好用!
    • 很高兴为您提供帮助
    【解决方案3】:

    类似于@Subash,但您也可以这样做:

    #this returns the match string of i which is truthy or false if no match.
    
    elsif "+-/*"[i] 
    

    如果你想返回一个布尔值 true 或 false 你也可以双击

    elsif !!"+-/*"[i] #true if matched, false if not
    

    在 ruby​​ 中有很多这样的变体,如果你有正则表达式或其他类型的字符串匹配,你也可以使用

    i = '/'
    !!"+-/*".match(i) #true
    

    【讨论】:

      猜你喜欢
      • 2014-06-17
      • 1970-01-01
      • 2023-03-26
      • 2012-03-04
      • 2019-12-31
      • 2015-11-05
      • 1970-01-01
      • 1970-01-01
      • 2016-07-27
      相关资源
      最近更新 更多