0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

case文で条件分岐 ❏Ruby❏

Last updated at Posted at 2019-11-24

使い方

対象の値が条件に合うかどうか調べます。
合っていたら処理を実行します。

case 対象
when 条件1
  条件1
when 条件2
  処理2
...
else
  処理3
end

例1

fruits = banana

case fruits
when "apple"
  puts "It's red!"
when "banana"
  puts "It's yellow"
when "orange"
  puts "It's orange"
else
  puts "I don't know"
end

結果
It's yellow

例2

score = 65

case score
when 90..100
  puts "A+"
when 80..89
  puts "A"
when 70..79
  puts "B"
when 60..69
  puts "C"
else
  puts "F"
end

結果
C

if文との使い分け

条件式といえば if文 が真っ先に思いつきます。
上の例も if文 で書き換えることも可能です。

では、どう使い分けるか。。。

基本 → if

条件式が複数あり、対象がすべて同じ場合 → case


僕はこうしてます。 caseを使ったほうが可読性は上がります。

より良い意見あったらコメントお願いします。


ではまた!
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?