Skip to content

Instantly share code, notes, and snippets.

@leifg
Created November 7, 2013 18:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leifg/7359417 to your computer and use it in GitHub Desktop.
Save leifg/7359417 to your computer and use it in GitHub Desktop.
Correctly check for empty/filled array
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