3.times { print "Ruby! " }
nil?, empty? and blank?

rubyquicktips:

In Ruby, you check with nil? if an object is nil:

article = nil
article.nil?  # => true

empty? checks if an element - like a string or an array f.e. - is empty:

# Array
[].empty?   #=> true
# String
"".empty?   #=> true

Rails adds the method blank? to the Object class:

An object is blank if it‘s false, empty, or a whitespace string. For example, “”, ” “, nil, [], and {} are blank.

This simplifies

if !address.nil? && !address.empty?

to

if !address.blank?

Documentation: nil?, empty? (String, Array) and blank?

As of Rails 2.3, there’s also a handy new try() method on objects, which allows you to invoke a method on a possibly nil object without throwing a NoMethodError. This saves you the trouble of checking if your object is nil or not before accessing a method.

For example, previously you’d need to do something like

article = Article.find_by_title("My Article")
unless article.nil? 
  article.body
end

With try() you can skip the nil? check and do the following

Article.find_by_title("My Article").try(:body) => #body or nil
blog comments powered by Disqus