views:

1941

answers:

5

I find myself repeatedly looking for a clear definition of the differences of nil?, blank?, and empty? in Ruby on Rails. Here's the closest I've come:

blank? objects are false, empty, or a whitespace string. For example, "", " ", nil, [], and {} are blank.

nil? objects are instances of NilClass.

empty? objects are class-specific, and the definition varies from class to class. A string is empty if it has no characters, and an array is empty if it contains no items.

Is there anything missing, or a tighter comparison that can be made?

+2  A: 

One difference is that .nil? and .empty? are methods that are provided by the programming language Ruby, whereas .blank? is something added by the web development framework Rails.

Andrew Grimm
+2  A: 

Don't forget any? which is generally !empty?. In Rails I typically check for the presence of something at the end of a statement with if something or unless something then use blank? where needed since it seems to work everywhere.

.any? doesn't work with strings in ruby 1.9, as .any? requires enumerable, and string#each by itself doesn't work in ruby 1.9.
Andrew Grimm
+18  A: 

.nil?

can be used on any object and is true if the object is nil

.empty?

can be used on strings, arrays and hashes and returns true if:

  • String length == 0
  • Array length == 0
  • Hash length == 0

running .empty? on something that is nil will throw a NoMethodError

That is where .blank? comes in. It is implemented by Rails and will operate on any object as well as work like .empty? on strings, arrays and hashes.

nil.blank? == true
[].blank? == true
{}.blank? == true
"".blank? == true
5.blank? == false

.blank? also evaluates true on strings which are non-empty but contain only whitespace.

"  ".blank? == true
"  ".empty? == false
Corban Brook
As mentioned in the question, some non-empty strings count as blank.
Andrew Grimm
Thanks for catching that.
Corban Brook
A: 

Just a little note about the any? recommendation: He's right that it's generally equivalent to !empty?. However, any? will return true to a string of just whitespace (ala " ").

And of course, see the 1.9 comment above, too.

orangechicken
A: 

Quick tip: !obj.blank? == obj.present?

Can be handy/easier on the eyes in some expressions

Alexander Malfait