Created
October 19, 2011 05:42
-
-
Save brookr/1297539 to your computer and use it in GitHub Desktop.
Comparison of existential checks in Rails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Does it have substance? Use .blank? or .present?, it's opposite: | |
| >> " ".blank? | |
| => true | |
| >> nil.blank? | |
| => true | |
| >> [].blank? | |
| => true | |
| >> nil.present? | |
| => false | |
| >> [].present? | |
| => false | |
| >> " ".present? | |
| => false | |
| # Anything at all in there? Use .any? as the opposite of .empty?. Watch out for nils: | |
| >> " ".empty? | |
| => false | |
| >> [].empty? | |
| => true | |
| >> nil.empty? | |
| NoMethodError: You have a nil object when you didn't expect it! | |
| You might have expected an instance of Array. | |
| The error occurred while evaluating nil.empty? | |
| >> " ".any? | |
| => true | |
| >> [].any? | |
| => false | |
| >> nil.any? | |
| NoMethodError: You have a nil object when you didn't expect it! | |
| You might have expected an instance of Array. | |
| The error occurred while evaluating nil.any? | |
| from (irb):38 | |
| # Is it numerically zero? Even the .zero? method has an opposite: .nonzero?. | |
| >> 0.zero? | |
| => true | |
| >> [].zero? | |
| NoMethodError: undefined method `zero?' for []:Array | |
| >> " ".zero? | |
| NoMethodError: undefined method `zero?' for " ":String | |
| >> 0.nonzero? | |
| => nil | |
| >> [].nonzero? | |
| NoMethodError: undefined method `nonzero?' for []:Array | |
| >> " ".nonzero? | |
| NoMethodError: undefined method `nonzero?' for " ":String | |
| # Is it actually nil? The opposite in this case is Ruby's boolean sense of an object itself: | |
| >> nil.nil? | |
| => true | |
| >> " ".nil? | |
| => false | |
| >> [].nil? | |
| => false | |
| >> true if nil | |
| => nil | |
| >> true if " " | |
| => true | |
| >> true if [] | |
| => true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment