4
2

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】nil? ・empty? ・blank? ・present?の使い方

Posted at

はじめに

使い分けがフワッとしていたので改めてまとめます。

メソッドごとの違い

メソッド 判定対象 出力
nil? nil Boolean
empty? ""(空文字) Boolean
blank? nil + ""(空文字) + [] + {} Boolean
present? nil + ""(空文字)以外か Boolean

nil?

hoge = nil
puts hoge.nil?
# true
hoge = ""
puts hoge.nil?
# false

empty?

hoge = ""
puts hoge.empty?
# true

hoge = "hoge"
puts hoge.empty?
# false

hoge = nil
puts hoge.empty?
#undefined method `empty?' for nil:NilClass (NoMethodError)

レシーバがnilの可能性がある場合は例外が吐かれる可能性がある。

blank?

hoge = ""
puts hoge.blank?
# true

hoge = "hoge"
puts hoge.blank?
# false

hoge = nil
puts hoge.blank?
# true

present?

hoge = ""
puts hoge.present?
# false

hoge = "hoge"
puts hoge.present?
# true

hoge = nil
puts hoge.present?
# false

!blankと等価の関係に当たる。

4
2
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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?