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?

条件分岐の様々な書き方

Posted at

はじめに

チェリー本で学習中に!!を用いた真偽値の型変換について学習した
他にも色々書き方あると考え列挙してみた

def user_exists?
   # データベースなどからユーザを探す(なければnil)
   user = find_user
   if user
     # userが見つかったのでtrue
     true
   else
     # userが見つからないのでfalse
     false
   end
end

# 上と同義(否定系の否定 = 結果をbooleanでそのまま返す)
def user_exists?
   !!find_user
end

三項演算子

# find_userメソッドがtureであればtureを返し、falseであればfalseを返す
def user_exists?
  find_user ? true : false
end

早期リターン

def user_exists?
  return true if user_find
  false
end

最後に

個人的人は三項演算子が読みやすい気がする

参考文献

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?