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?

Ruby/Rails】if文を短縮してRubocopに怒られない書き方まとめ

0
Last updated at Posted at 2026-03-17

【Ruby/Rails】if文を短縮してRubocopに怒られない書き方まとめ

はじめに

Rails や Ruby でコードを書いていると、どうしても if 文が長くなりがちです。
しかも Rubocop に「もっと短く書け!」と警告されることもあります。

この記事では if文をスッキリ書く方法 をいくつか紹介します。
Rubocop もニッコリして、コードも読みやすくなりますよ 😇

1. 三項演算子(?:)

条件に応じて 値を返したい ときは三項演算子が便利です。

before
if score >= 80
  puts '合格'
elsif score >= 60
  puts '追試'
end
after
message = score >= 80 ? '合格' : '不合格'
puts message

三項演算子は「処理を行う」のではなく 値を返す 構文です。
代入やメソッド引数など、値が必要な場面で使いましょう。

別の例👇

before
x = 5
if x > 0
  'positive'
else
  'negative'
end
after
x = 5
y = x > 0 ? 'positive' : 'negative'

2. 論理演算子を使う(&& / ||)

短い処理なら論理演算子でも書けます。

真の場合のみ処理

ruby
x = 5
x > 0 && puts 'positive'

偽の場合のみ処理

ruby
x = 5
x > 0 || puts 'negative'

3. 修飾 if / unless

if を後ろに付けるスタイル。
Ruby/Rails ではめちゃくちゃよく使われます。

ruby
x = 5
puts 'positive' if x > 0

偽の場合は unless が読みやすい。

ruby
x = 5
puts 'negative' unless x >= 0

まとめ

• 値を返す → 三項演算子
• 単発の処理 → 論理演算子 or 修飾 if/unless
• Rubocop にも怒られないし、コードも読みやすくなる
使い分け早見表
目的 書き方 例
値を返す 三項演算子 y = x > 0 ? 'pos' : 'neg'
真の場合実行 && / if puts 'OK' if cond
真の場合実行 || / unress puts 'NG' unless cond

これで Rubocop もニッコリ、レビューアーも読みやすいスッキリコードになります ✨

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?