Case语句在每个'when'块中有多个值

我可以描述我正在寻找的最佳方式是向您展示迄今为止我尝试过的失败代码:

case car
  when ['honda', 'acura'].include?(car)
    # code
  when 'toyota' || 'lexus'
    # code
end

when大约50种不同的可能的car价值应该触发的情况下,我有大约4或5种不同的情况。 有没有办法做到这一点的case或者我应该尝试一个巨大的if块?


在一个case声明,一,是相当于||if语句中。

case car
   when 'toyota', 'lexus'
      # code
end

Ruby case语句可以做的其他一些事情


你可能会利用ruby的“splat”或扁平化语法。

when条款when会长满 - 如果我理解正确的话,你有大约10个值来测试每个分支 - 在我看来,它更具可读性。 另外,您可以修改要在运行时测试的值。 例如:

honda  = ['honda', 'acura', 'civic', 'element', 'fit', ...]
toyota = ['toyota', 'lexus', 'tercel', 'rx', 'yaris', ...]
...

if include_concept_cars:
  honda += ['ev-ster', 'concept c', 'concept s', ...]
  ...

case car
when *toyota
  # Do something for Toyota cars
when *honda
  # Do something for Honda cars
...
end

另一种常见的方法是使用散列作为调度表,每个car值和值都有一个键,这些键是一些可调用的对象,用于封装您希望执行的代码。


将数据放入逻辑的另一个好方法是这样的:

# Initialization.
CAR_TYPES = {
  foo_type: ['honda', 'acura', 'mercedes'],
  bar_type: ['toyota', 'lexus']
  # More...
}
@type_for_name = {}
CAR_TYPES.each { |type, names| names.each { |name| @type_for_name[type] = name } }

case @type_for_name[car]
when :foo_type
  # do foo things
when :bar_type
  # do bar things
end
链接地址: http://www.djcxy.com/p/25829.html

上一篇: Case statement with multiple values in each 'when' block

下一篇: ruby/rails block content problem