LoginSignup
19
25

More than 5 years have passed since last update.

Rubyの条件分岐

Last updated at Posted at 2015-05-29

if

条件を元に処理を分岐させたい場合に、ifを使う。

n = 2

if n.zero?
 puts '0でした'
elsif n.even?
 puts '偶数'
elsif n.odd?
 puts '奇数'
else
 puts 'わかりません'
end

unless

unlessはifと逆の動きをする

n = 1
unless n.zero?
 puts '0ではない'
else
 puts '0です'
end

then

thenは任意でつける事が可能。つけた場合に処理を1行で書ける。

if n.zero? then puts '0です' else puts '0ではない' end

三項演算子

上記はあまり利用されないので、もっと綺麗に書くなら三項演算子を使える。

result = n.zero? ? '0でした' : '0ではない'
puts result

後置if

else節にあたる分岐が無ければ、後置ifがつかえる。

puts '0だった' if n.zero?
19
25
2

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
19
25