【问题标题】:Implementing the 'case' statement in order to match multiple 'when' conditions实现“case”语句以匹配多个“when”条件
【发布时间】:2011-07-09 23:17:16
【问题描述】:

我正在使用 Ruby on Rails 3,我想使用 case 语句,即使在匹配 when 语句之后,也可以继续检查其他 when statement 直到最后一个 else

例如

case var
when '1'
  if var2 == ...
    ...
  else
    ...
    puts "Don't make nothig but continue to check!"
    # Here I would like to continue to check if a 'when' statement will match 'var' until the 'else' case
  end
when '2'
  ...
...
else
  put "Yeee!"

结束

在 Ruby 中可以吗?如果有,怎么做?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 switch-statement conditional-statements


    【解决方案1】:

    我看到的大部分来自 ruby​​ 的代码都是用 if elsif else 完成的,但你可以模仿类似于其他语言的 switch 逻辑表达式,如下所示:

    case var
    when 1
      dosomething
    when 2..3
      doSomethingElse
    end
    
    case
    when var == 1
       doSomething
    when var < 12
       doSomethingElse
    end
    

    来自SO Question。就像我说的,这通常是在 ruby​​ 中使用 if elsif else 完成的,例如:

    if my_number == "1"
       #do stuff when equals 1
    elsif my_number == "e"
       #same thing here
    else
       #default, no case found
    end 
    

    【讨论】:

      【解决方案2】:

      Ruby 对case 没有任何形式的失败。

      另一种选择是使用=== 方法的一系列if 语句,case 在内部使用该方法来比较项目。

      has_matched? = false
      
      if '2' === var
        has_matched? = true
        # stuff
      end
      
      if '3' === var
        has_matched? = true
        # other stuff
      end
      
      if something_else === var
        has_matched? = true
        # presumably some even more exciting stuff
      end
      
      if !has_matched?
        # more stuff
      end
      

      这有两个明显的问题。

      1. 不是很DRYhas_matched? = true 到处都是垃圾。

      2. 您始终需要记住将var 放在=== 的右侧,因为这是case 在幕后所做的。

      您可以使用封装此功能的matches? 方法创建自己的类。它可能有一个构造函数来获取您将要匹配的值(在本例中为var),并且它可能有一个else_do 方法,该方法仅在其内部@has_matched? 实例变量仍然为假时才执行其块.

      编辑:

      === 方法可以表示任何你想要的意思。一般来说,这是一种更“宽容”的方式来测试两个对象之间的等效性。这是this page的一个例子:

      class String
        def ===(other_str)
          self.strip[0, other_str.length].downcase == other_str.downcase
        end
      end
      
      class Array
        def ===(str)
          self.any? {|elem| elem.include?(str)}
        end
      end
      
      class Fixnum
        def ===(str)
          self == str.to_i
        end
      end
      

      本质上,当 Ruby 遇到 case var 时,它会在您正在比较的对象上调用 === var

      【讨论】:

      • Ruby 有一个案例。这是“其他”。
      猜你喜欢
      • 2022-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-04
      • 1970-01-01
      • 2023-02-07
      • 2016-03-12
      • 1970-01-01
      相关资源
      最近更新 更多