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?

return文の使い方(ガード節)

Posted at

✅ ガード節とは?
条件に当てはまったらすぐに return などで抜ける書き方のこと。

主に「例外的なケースを先に処理して、メインの処理をシンプルにする」ために使う。

🔁 ふつうの if〜else 書き方(比較用)

def greet(name)
  if name.nil?
    return "名前がありません"
  else
    return "こんにちは、#{name}さん"
  end
end

✅ ガード節を使った書き方

def greet(name)
  return "名前がありません" if name.nil?
  "こんにちは、#{name}さん"
end

⬅ これがガード節!
if の条件を先にチェックして

当てはまったらすぐ return などで抜ける

それ以外の処理は最後にまとめて書ける

def mixer(fruit)
  return "入力が空です" if fruit.empty?
  return "数字はダメです" if fruit.match?(/\d/)

  "#{fruit}ジュース"
end

こうすれば、例外処理が上にまとまって、メイン処理(ジュース化)がスッキリ書ける。

💡ガード節を使うメリット
メリット 説明
読みやすい 例外ケースを上に書くので、パッと読める
ネストが浅くなる else を使わないのでコードが深くならない
バグが減る 「例外は早めに返す」が基本の考え方になる

✅ よくある使い方パターン
① nilチェック

return "値がありません" if value.nil?

② 空チェック

return "空文字です" if str.empty?

③ 数値チェック

return "数値ではありません" unless num.is_a?(Integer)

🔚 まとめ
ガード節とは「先に抜け道をつくる書き方」

return if ... で処理を途中終了

else を使わずスッキリ書ける

Rubyではすごくよく使われる書き方

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?