Forked from pythonicrubyist/nil_empty_blank_present_ffdierence_in_ruby
Created
August 24, 2020 16:08
-
-
Save gauravds/f2a3eeb98ea76f4a45a12af5bd994acb to your computer and use it in GitHub Desktop.
Difference between nil?, empty?, blank? and present? in Ruby and Ruby on Rasils.
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
# nil? can be used on any Ruby object. It returns true only if the object is nil. | |
nil.nil? # => true | |
[].nil? # => false | |
{}.nil? # => false | |
"".nil? # => false | |
" ".nil? # => false | |
true.nil? # => false | |
# empty? can be used on some Ruby objects including Arrays, Hashes and Strings. It returns true only if the object's length is zero. | |
nil.empty? # NoMethodError: undefined method `empty?' for nil:NilClass | |
[].empty? # => true | |
{}.empty? # => true | |
"".empty? # => true | |
" ".empty? # => true | |
true.empty? # => NoMethodError: undefined method `empty?' for true:TrueClass | |
# blank? is an ActiveSupport extension to Ruby Object and returns true for nil, false, empty, or a white-space string. | |
[ "", " ", false, nil, [], {} ].all?(&:blank?) # => true | |
# present? is also an ActiveSupport extension to Ruby Object and it is the negation of blank? | |
[ "", " ", false, nil, [], {} ].any?(&:present?) # => false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment