Updated May 2020
Ruby methods can seem pretty daunting to a new programmer and knowing when to use which one can feel like a giant black hole. In this guide, I wanted to put together a quick cheatsheet for using some of the most common methods in Ruby and Rails —
.nil? .empty? .blank? and .present?
Remember your first day of learning Ruby when you were told that pretty much everything is an object? Well, nil is also its own class. Checking for .nil? will only return true if the object itself is nil. That means that an empty string is NOT nil and an empty array is NOT nil. Neither is something that is false nil.
=> true "".nil?
For more info on .nil and NilClass, check out this sweet Ruby Guides article!
.empty means that the length object you are trying to evaluate == 0. It’s primarily used for hashes, strings, and array
NoMethodError: undefined method `empty?' for nil:NilClassfalse.empty?
NoMethodError: undefined method `empty?' for false:FalseClass"".empty?
=> true" ".empty?
=> true[ ].empty?
.blank? is a rails method and solves the issue of the ugly error you get when checking if something nil is empty. This is an ActiveRecord method that exists for any Rails object and will return true for nil, false, empty, or a whitespace string.
=> true " ".blank?
=> true (different from .empty?).blank?
Also a Rails method (meaning it won’t work in your irb console), .present? is just the opposite of .blank?
In other terms:
!object.blank? == object.present?
.exists? has been deprecated since Rails 3, so don’t use .exists? It’s more of a search query, but it gets grouped with the methods above quite a bit, so I wanted to mention it here just in case. .
Which Rails topic should I cover next? If you enjoyed this article, I would love if you guys clap or leave a comment below! Thank you for reading!