Possible Duplicate:
A concise explanation of nil v. empty v. blank in Ruby on Rails
Can anyone tell me the difference between nil?
, blank?
and empty?
in Ruby?
blank (adjective) - not written or printed on. empty (adjective) - containing nothing; not filled or occupied.
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.
Well, nil is a special Ruby object used to represent an “empty” or “default” value.
In Ruby, nil is a special value that denotes the absence of any value. Nil is an object of NilClass. nil is Ruby's way of referring to nothing or void.
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 an earlier question, "How to understand nil vs. empty vs. blank in Rails (and Ruby)", so you should check the answers to that too.
Feel it ;)
NIL?
nil.nil? #=> true [].nil? #=> false "".nil? #=> false " ".nil? #=> false
EMPTY?
[].empty? #=> true nil.empty? #=> undefined method "".empty? #=> true " ".empty? #=> false
BLANK?
[].blank? #=> true nil.blank? #=> true "".blank? #=> true " ".blank? #=> true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With