Table of contentsClick link to navigate to the desired location
This content has been automatically translated from Ukrainian.
Methods are often seen in Ruby and Rails blank?, present?, empty? i nil?. They seem similar, but actually have different sources and behaviors. Let's figure out when which method should be used.
nil? - basic Ruby method
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
Used to check if there is an object at all.
empty? — for collections and lines
Method empty? defined in the classes of String, Array, Hash, Set, and some others. He checks whether collection or string is empty, that is, they do not contain elements or symbols.
".empty? # => true
[].empty? # => true
{}.empty? # => true
nil.empty? # => NoMethodError
If the object does not support empty?, get an error. Therefore, this method should only be used when you know exactly the type of variable.
blank? - with ActiveSupport (Rails)
Method blank? appears thanks to the library ActiveSupport, which goes with Rails. It is a more "smart" 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? convenient to use in Rails code when you want to check the “void” of any object without exception.
present? - with ActiveSupport (Rails)
The present method? is simply the opposite blank?. It returns true if the object not empty.
"Ruby".present? # => true "".present? # => false nil.present? # => false [1, 2].present? # => true
Used for conditions:
puts "Hello!" if name.present?
Briefly:
- nil? - standard Ruby, only checks nil.
- empty? - standard Ruby, for collections and lines, etc.
- blank? - with ActiveSupport, takes into account nil, spaces, and empty collections.
- present? - with ActiveSupport, opposite to blank?.
When to use something
- If you write pure Ruby without Rails - use nil? and empty?.
- If you have Rails or ActiveSupport - more often convenient blank? /present?, because they cover all cases and do not cause errors on nil.
This post doesn't have any additions from the author yet.