case...when...else...end

case 语句使用 === 匹配运算符,将 case 表达式的结果与 when 表达式的每个结果进行匹配。when 子句的数量可以是任意的,但是只计算第一个匹配 when 子句主体的值。如果没有匹配的 when 子句,然而程序员提供了 else 子句,则会对 else 子句的主体进行求值。如果既没有匹配的 when 子句,又没有 else 子句,则 case 表达式将返回空值。

 case degrees_in_kelvin
 when 0..273
   puts "solid"
 when 274..372
   puts "liquid"
 else

   puts "gas"
 end

case...when..else..end 结构决定了 === 方法的匹配行为。The default === method inherited from Object is an equality test using equal? which performs strict object equality. This method is implemented as an alias, however, so redefining the equals? method on a subclass will not change the behavior of the default inherited === method.

很多核心类(如 RegExp 和 Range)都提供了 === 方法,它可匹配整个对象组。

 case "hello"
 when /^ye/
   puts "yee-haw"    
 when /^he/
   puts "hee-haw"
 end

在执行匹配时,when 表达式中的对象是调用方,case 表达式中的对象是参数。在上面的示例中,成功找到了以下表达式的匹配项:/^he/ === "hello"。

与大多数 Ruby 特殊窗体类似,case...when...else...end 表达式返回其结果。这是在块内进行求值的最后一个表达式的结果。

 puts case x
      when 0...10
        puts "this is not the value"
        0 # but this will be if x is in between 0 and 10
      when 10...100
        1
      when 100...1000
        2
      end