How to use .nil? .empty? .blank? .present? in Rails 6

How to use .nil? .empty? .blank? .present? in Rails 6

Image for post

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?

Check out my other articles in this series on using acts_as_taggable_on and the devise gems with Rails 5!

Image for postA quick cheatsheet so you don?t have to read the full article 😉

.nil? [RUBY]

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.

nil.class=> NilClassnil.nil? => true “”.nil? => falsefalse.nil? => false.nil? => false

For more info on .nil and NilClass, check out this sweet Ruby Guides article!

.empty? [RUBY]

.empty means that the length object you are trying to evaluate == 0. It?s primarily used for hashes, strings, and array

nil.empty? NoMethodError: undefined method `empty?’ for nil:NilClassfalse.empty? NoMethodError: undefined method `empty?’ for false:FalseClass””.empty? => true” “.empty? => false.empty? => true[ ].empty? => true

.blank? [RAILS]

.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.

nil.blank?=> truefalse.blank?=> true “”.blank? => true ” “.blank? => true (different from .empty?).blank? => true{}.blank?=> true

.present? [RAILS]

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? [RAILS]

.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!


No Responses

Write a response