Possible Duplicate:
A concise explanation of nil v. empty v. blank in Ruby on Rails
Could anyone tell me the difference between .nil?, .blank?, .empty? in ruby?
Any answer will be highly appreciated.
Answer
In Ruby, nil
in an object (a single instance of the class NilClass
). This means that methods can be called on it. nil?
is a standard method in Ruby that can be called on all objects and returns true
for the nil
object and false
for anything else.
empty?
is a standard Ruby method on some objects like Arrays, Hashes and Strings. Its exact behaviour will depend on the specific object, but typically it returns true
if the object contains no elements.
blank?
is not a standard Ruby method but is added to all objects by Rails and returns true
for nil
, false
, empty, or a whitespace string.
Because empty?
is not defined for all objects you would get a NoMethodError
if you called empty?
on nil
so to avoid having to write things like if x.nil? || x.empty?
Rails adds the blank?
method.
After answering, I found that this question has been asked before so you should check the answers to that question too.
No comments:
Post a Comment