Table of contentsClick link to navigate to the desired location
This content has been automatically translated from Ukrainian.
In Ruby and Rails, you often see the methods blank?, present?, empty?, and nil?. They seem similar, but actually have different origins and behaviors. Let's figure out when to use each method.
nil? - basic Ruby method
The nil? method is part of Ruby. It returns true if the object is exactly nil.
nil.nil? # => true "".nil? # => false [].nil? # => false 0.nil? # => false
It is used to check whether an object exists at all.
empty? — for collections and strings
The empty? method is defined in the String, Array, Hash, Set classes, and some others. It checks whether the collection or string is empty, meaning it contains no elements or characters.
"".empty? # => true
[].empty? # => true
{}.empty? # => true
nil.empty? # => NoMethodError
If an object does not support empty?, you will get an error. Therefore, this method should only be used when you are sure of the variable's type.
blank? - from ActiveSupport (Rails)
The blank? method comes from the ActiveSupport library that comes with Rails. It is a more "intelligent" version of empty? because it takes into account nil, spaces, and empty collections.
nil.blank? # => true
"".blank? # => true
" ".blank? # => true
[].blank? # => true
{}.blank? # => true
false.blank? # => true
0.blank? # => false
blank? is convenient to use in Rails code when you need to check the "emptiness" of any object without exceptions.
present? - from ActiveSupport (Rails)
The present? method is simply the opposite of blank?. It returns true if the object is not empty.
"Ruby".present? # => true "".present? # => false nil.present? # => false [1, 2].present? # => true
It is used for conditions:
puts "Hello!" if name.present?
In short:
- nil? - standard Ruby, checks only for nil.
- empty? - standard Ruby, for collections and strings, etc.
- blank? - from ActiveSupport, considers nil, spaces, and empty collections.
- present? - from ActiveSupport, the opposite of blank?.
When to use what
- If you are writing pure Ruby without Rails - use nil? and empty?.
- If you have Rails or ActiveSupport - it is often more convenient to use blank? / present?, as they cover all cases and do not raise errors on nil.
This post doesn't have any additions from the author yet.