在每个‘when‘块中具有多个值的Case语句

本文翻译自: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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值