15
14

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.

Rails: nil?, empty?, blank?, present?の挙動

Last updated at Posted at 2014-09-12

Rails開発でnil?, empty?, blank?, present?の挙動にハマったのでメモ

以下の値で書くメソッドについて比較してみる。

var.rb
a = nil
b = true
c = false
d = []
e = [123]
f = 123

nil?

nil.rb
a.nil? #=> true
b.nil? #=> false
c.nil? #=> false
d.nil? #=> false
e.nil? #=> false 

empty?

empty.rb
a.empty? #=> undefined method `empty?' for nil:NilClass
b.empty? #=> undefined method `empty?' for true:TrueClass
c.empty? #=> undefined method `empty?' for false:FalseClass
d.empty? #=> true
e.empty? #=> false
f.empty? #=> undefined method `empty?' for 123:Fixnum

blank?

blank.rb
a.blank? #=> true
b.blank? #=> false
c.blank? #=> true
d.blank? #=> true
e.blank? #=> false
f.blank? #=> false

present?

present.rb
a.present? #=> false
b.present? #=> true
c.present? #=> false
d.present? #=> false
e.present? #=> true
f.present? #=> true

Rubyの条件式を用いた場合

if.rb
puts a ? true : false #=> false
puts b ? true : false #=> true
puts c ? true : false #=> false
puts d ? true : false #=> true
puts e ? true : false #=> true
puts f ? true : false #=> true
15
14
2

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
15
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?