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

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

我有大约4到5个不同的情况应该由大约50个不同的car值触发。有办法做到这一点的情况块或我应该尝试一个巨大的if块?


当前回答

记住switch/case (case/when,等等)只是比较值。我喜欢在这个例子中对简单或'd字符串列表进行比较的官方答案,但对于更奇特的条件/匹配逻辑,

case true
  when ['honda', 'acura'].include?(car)
    # do something
  when (condition1 && (condition2 || condition3))
    # do  something different
  else
    # do something else
end

其他回答

在case语句中,相当于if语句中的&&。

案例coding_language 当'ror' && 'javascript' #代码 结束

在case语句中,a相当于if语句中的||。

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

使用Ruby case语句还可以做其他一些事情

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

# 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

你可以这样做(灵感来自@pilcrow的回答):

honda  = %w[honda acura civic element fit ...]
toyota = %w[toyota lexus tercel rx yaris ...]

honda += %w[ev_ster concept_c concept_s ...] if include_concept_cars

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

记住switch/case (case/when,等等)只是比较值。我喜欢在这个例子中对简单或'd字符串列表进行比较的官方答案,但对于更奇特的条件/匹配逻辑,

case true
  when ['honda', 'acura'].include?(car)
    # do something
  when (condition1 && (condition2 || condition3))
    # do  something different
  else
    # do something else
end