Created
January 25, 2014 23:12
-
-
Save armw4/8625203 to your computer and use it in GitHub Desktop.
Don't sleep on arrays. When looking for a "truthy" value, you need to ensure the array has been initialized (not nil), AND also that it's length is a positive integer.
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
my_array = [] | |
puts "It's alive" if my_array # truthy...empty array does not return false | |
puts "It's alive" if my_array.length # truthy again....0 does not return false | |
# the ultimate truthy test for arrays...finally we get back false..hence no output | |
puts "It's alive" if my_array && my_array.length > 0 |
I'd also like to add that in most cases the additional check against the length
of the array will be redundant. Reason being is because 9/10, you'll be iterating via some looping construct like:
my_array.each do |item|
# operate on item
end
The core looping constructs will not even execute your code if there are no items present in your Enumerable
. This is equivalent to your standard foreach...
in C# or Java.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A JavaScript array's
length
would however returnfalse
if it were0
. You'd be able to get away with:my_array && my_array.length