Saturday, June 1, 2019

ruby - Difference between .nil?, .blank? and .empty?





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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...