0
0

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 3 years have passed since last update.

if文以外の条件分岐を使ってみる

Posted at

Rubyの条件分岐はif文の他にもunlessという方法もあります。
if文は、条件式がtrueの場合に処理が実行され、falseのときはelseの後に記述した処理が実行されます。

if 条件式
  条件式がtrueの時に実行する処理
else
  条件式がfalseの時に実行する処理
end

unless文は条件式がfalseの場合に処理が実行され、trueのときはelseの後に記述した処理が実行されます。

unless 条件式
  条件式がfalseの時に実行する処理
else
  条件式がtrueの時に実行する処理
end

例えば、

if a + b > 0
  puts "計算結果は0より大きいです"
end

のif文をunless文を使って記述したとすると、

unless a + b <= 0
  puts "計算結果は0より大きいです" 
end

if文では0が含まれていないので、unless文では0以上とすることで同じような意味になります。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?