1つの値と一致するものを複数の値の中から探すような場合は、if文でelsifを積み重ねていくよりも、case文で書いた方がシンプルに記述することができる。
if文を使用すると以下のようになるものを
time_zone = "evening"
if time_zone == "morning"
puts "おはよう"
elsif time_zone == "afternoon"
puts "こんにちは"
elsif time_zone == "evening"
puts "こんばんは"
else
puts "おやすみ"
end
case文に書き換えると
time_zone = "evening"
case time_zone
when "morning"
puts "おはよう"
when "afternoon"
puts "こんにちは"
when "evening"
puts "こんばんは"
else
puts "おやすみ"
end
このようになり、繰り返し記述していたtime_zone == を省くことができる。