本文翻译自:Case statement with multiple values in each 'when' block
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 when
situations that should be triggered by approximately 50 different possible values of car
. when
有大约50种不同可能的car
值触发的情况时,我有大约4或5种不同的情况。 Is there a way to do this with case
blocks or should I try a massive if
block? 有没有办法用case
块做这个或者我应该尝试一个巨大的if
块?
#1楼
参考:https://stackoom.com/question/GMLQ/在每个-when-块中具有多个值的Case语句
#2楼
In a case
statement, a ,
is the equivalent of ||
在case
语句中,a ,
相当于||
in an if
statement. 在if
语句中。
case car
when 'toyota', 'lexus'
# code
end
Some other things you can do with a Ruby case statement 使用Ruby case语句可以做的其他一些事情
#3楼
You might take advantage of ruby's "splat" or flattening syntax. 您可以利用ruby的“splat”或flattening语法。
This makes overgrown when
clauses — you have about 10 values to test per branch if I understand correctly — a little more readable in my opinion. 这使得杂草丛生when
条款-您有10个值每个分支来测试,如果我理解正确的话-在我看来有点更具可读性。 Additionally, you can modify the values to test at runtime. 此外,您可以修改要在运行时测试的值。 For example: 例如:
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 car
and values that are some callable object encapsulating the code you wish to execute. 另一种常见的方法是使用散列作为调度表,使用每个car
值的键和值,这些值是一些可调用对象,封装了您希望执行的代码。
#4楼
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