0
0

case文

Last updated at Posted at 2024-06-30

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 == を省くことができる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0