How to use .nil? .empty? .blank? .present? in Rails 6
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!
.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!