up vote 7 down vote favorite 1 | 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?
| ||||
up vote 17 down vote accepted | .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:
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.
.blank? also evaluates true on strings which are non-empty but contain only whitespace.
| ||||||||||||||
|
up vote 2 down vote | 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. | ||||
up vote 2 down vote | Don't forget | ||||||||
|
up vote 0 down vote | Just a little note about the And of course, see the 1.9 comment above, too. | ||||
up vote 0 down vote | Quick tip: Can be handy/easier on the eyes in some expressions |