Friedrich Ewald My Personal Website

Ruby on Rails nil check

Rails provides a great way to check for nil and empty variables in the same call: blank?. This is especially helpful in ERB templates where a variable can be either nil or empty, depending on the object. Without it, the check would look similar to this:

<% unless obj.nil? and obj != "" %>
    <%= obj %>
<% end %>
This is quite cumbersome and easy to forget. With blank?, this can be simplified to:
<% unless obj.blank? %>
    <%= obj %>
<% end %>
For the following values blank? returns true and false respectively:
"".blank?
=> true

nil.blank?
=> true

"hello".blank?
=> false

5.blank?
=> false

AnyClass.blank?
=> false


About the author

is an experienced Software Engineer with a Master's degree in Computer Science. He started this website in late 2015, mostly as a digital business card. He is interested in Go, Python, Ruby, SQL- and NoSQL-databases, machine learning and AI and is experienced in building scalable, distributed systems and micro-services at multiple larger and smaller companies.