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

Maria Schuessler
Le Wagon
Published in
2 min readJul 18, 2018

--

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!

A 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
=> NilClass
nil.nil?
=> true
"".nil?
=> false
false.nil?
=> false
[].nil?
=> false

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

.empty? [RUBY]

--

--

Maria Schuessler
Le Wagon

Music Product @ TikTok | Former Full-Stack Dev | Editor of StirCrazy! Mag | London-based | skippingcustoms.com