Skip to content

Instantly share code, notes, and snippets.

@armw4
Created January 25, 2014 23:12
Show Gist options
  • Save armw4/8625203 to your computer and use it in GitHub Desktop.
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.
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
@armw4
Copy link
Author

armw4 commented Jan 25, 2014

A JavaScript array's length would however return false if it were 0. You'd be able to get away with:

my_array && my_array.length

@armw4
Copy link
Author

armw4 commented Jan 25, 2014

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