实现'case'语句以匹配多个'when'条件

use*_*052 5 ruby ruby-on-rails switch-statement conditional-statements ruby-on-rails-3

我正在使用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!"
Run Code Online (Sandbox Code Playgroud)

结束

Ruby中有可能吗?如果是这样,怎么样?

Clo*_*boy 1

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
Run Code Online (Sandbox Code Playgroud)

这有两个明显的问题。

  1. 它不是很干燥has_matched? = true到处都是垃圾。

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

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

编辑:

===方法可以表示您希望它表示的任何含义。一般来说,这是测试两个对象之间的等效性的更“宽容”的方式。这是本页的一个示例:

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
Run Code Online (Sandbox Code Playgroud)

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