Created
November 7, 2013 18:23
-
-
Save leifg/7359417 to your computer and use it in GitHub Desktop.
Correctly check for empty/filled array
This file contains 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
arr = [] | |
# You probably know this one: | |
#http://ruby-doc.org/core-2.0.0/Array.html#method-i-empty-3F | |
if arr.empty? | |
# do something | |
end | |
# But do you also know the opposite? | |
arr = ['array', 'with', 'stuff', 'in', 'it'] | |
unless arr.empty? | |
# do something | |
end | |
# nice try, but there is also a predicate | |
# http://ruby-doc.org/core-2.0.0/Enumerable.html#method-i-any-3F | |
if arr.any? | |
# do something | |
end | |
# Hey, but what about nil values? | |
if arr && arr.any? | |
# do something | |
end | |
if arr.nil? ||arr.empty? | |
# do something | |
end | |
# If you have ActiveSupport you can do this with one predicate: | |
# for empty arrays: | |
# http://api.rubyonrails.org/classes/Object.html#method-i-blank-3F | |
if arr.blank? | |
# do something | |
end | |
# for filled arrays: | |
# http://api.rubyonrails.org/classes/Object.html#method-i-present-3F | |
if arr.present? | |
# do something | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment