各「when」ブロックに複数の値を持つcase文 質問する

各「when」ブロックに複数の値を持つcase文 質問する

私が探しているものを説明する最良の方法は、これまで試した失敗したコードを示すことです。

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

when約 50 種類の異なる値によってトリガーされる4 つか 5 つの異なる状況がありますcar。ブロックを使用してこれを実行する方法はありますcaseか、それとも大規模なブロックを試す必要がありますかif?

ベストアンサー1

文ではcase、 は文の,と同等です。||if

Ruby の case 式

case car
when 'toyota', 'lexus'
  puts 'brand is part of the Toyota Motor Corporation'
else
  puts 'some other brand'
end

# NOTE: You may use `then` after the when condition.
#       It is frequently used to place the body of the `when` on a single line.
case car
when 'toyota', 'lexus' then puts 'brand is part of the Toyota Motor Corporation'
else puts 'some other brand'
end

おすすめ記事