44
37

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

Rubyでreturnを使って条件分岐をシンプルに書く方法

Last updated at Posted at 2018-08-30

#はじめに

条件分岐のネストが深くなると可読性が落ちてしまいます。
しかし、returnを使って「早期復帰」させることで条件分岐をシンプルに書くことができます。

条件分岐でreturnを使う方法

まず、以下がreturnを使わずに書いたとき。ネストが深くてパッと見分かりにくいですよね。
room.present?じゃない時でもtrueを返すけど、SPECIAL_ROOM_NUMがある時だけはfalseを返すっていう処理です。


class Room
  SPECIAL_ROOM_NUM = [104, 204, 304].freeze

  def stayable?(room)
    if room.present?
      if SPECIAL_ROOM_NUM.include?(room)
        false
      else
        true
      end
    else
      true
    end
  end
end

returnを使って書いたのが以下。Rubyだと後置ifや後置unlessが使えるので一行で書くことができます。
present?の逆はblank?なので、room.blank?の時にtrueを返すよ、っていう処理にします。
さらにSPECIAL_ROOM_NUMを含んでいる時にはfalseを返すようにという書き方もできて、さらにDRYなコードにできますね。


class Room
  SPECIAL_ROOM_NUM = [104, 204, 304].freeze

  def stayable?(room)
    return true if room.blank?
    return false if SPECIAL_ROOM_NUM.include?(room)
    true
  end
end
44
37
6

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
44
37

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?