Ruby-on-rails 每个 'when' 块中具有多个值的 Case 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10197254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 03:14:19  来源:igfitidea点击:

Case statement with multiple values in each 'when' block

ruby-on-railsrubysyntaxswitch-statement

提问by Nick

The best way I can describe what I'm looking for is to show you the failed code I've tried thus far:

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

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

I've got about 4 or 5 different whensituations that should be triggered by approximately 50 different possible values of car. Is there a way to do this with caseblocks or should I try a massive ifblock?

我有大约 4 或 5 种不同的when情况,应该由大约 50 个不同的car. 有没有办法用case块来做到这一点,还是我应该尝试一个大块if

回答by Charles Caldwell

In a casestatement, a ,is the equivalent of ||in an ifstatement.

case语句中,a,相当于||inif语句。

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

Some other things you can do with a Ruby case statement

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

回答by pilcrow

You might take advantage of ruby's "splat" or flattening syntax.

您可以利用 ruby​​ 的“splat”或扁平化语法。

This makes overgrown whenclauses — you have about 10 values to test per branch if I understand correctly — a little more readable in my opinion. Additionally, you can modify the values to test at runtime. For example:

这使得过度增长的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', ...]
  ...
end

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

Another common approach would be to use a hash as a dispatch table, with keys for each value of carand values that are some callable object encapsulating the code you wish to execute.

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

回答by Hew Wolff

Another nice way to put your logic in data is something like this:

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

# 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