nil?, empty? and blank?
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? #=> trueRails adds the method
blank?to theObjectclass: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?
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
-
foreclosure-listings reblogged this from michaelbulat
-
accutane-lawsuit liked this
-
k776 liked this
-
ecleel liked this
-
ochronus liked this
-
l0c liked this
-
curtisgwapo liked this
-
curtisgwapo reblogged this from rubyquicktips
-
michaelbulat reblogged this from rubyquicktips and added:
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...
-
rubyquicktips posted this