LoginSignup
4
5

More than 5 years have passed since last update.

rubyにおける条件分岐(case,if)

Last updated at Posted at 2017-07-26

条件分岐について

〜な時に〜の処理をするというもの。rubyではcaseとifどちらも使える

ifによる条件分岐

test
score = 80
if score > 90
  puts "great!"
elsif score > 70
  puts "so so"
else
  puts "bad"
end

elsifで条件を追記することができ、上から順に条件にあったものの処理を行う。

test

if score > 90 then

上記のように後ろにthenを入れてもいいが省略してもいいので基本は省略。

caseによる条件分岐

test

case signal
when "red"
  puts "stop"
when "green","blue"
  puts "go"
else
  puts "go"
end

caseで対象オブジェクトを指定し、そのオブジェクトがなにかによって条件分岐を行う。

比較演算子について

長くなりそうだから他にまとめる

caseとifの使い分け

caseとifの違いは比較対象の個数の違いが大きく、caseはcaseの後に指定したもののみで条件分岐をできるがifは複数の対象を使い、条件分岐ができる。

4
5
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
4
5