Be Cool with Arrays

March 14, 2011 · 1 min read

A few of my pet peeves centre around arrays. Ruby gives you a beautifully expressive language for working with collections – use it. Your code will be more readable, and your future self will thank you.

Ask an array if it’s empty. Don’t check if its size equals zero.

bookmarks.size == 0 # no!
bookmarks.empty? # yes

Ask an array if it has any elements. Don’t check if it has a non-zero size.

bookmarks.size > 0 # no!
bookmarks.any? # yes

Don’t guard each with an emptiness check. It already handles empty arrays gracefully – it simply won’t yield.

if bookmarks.any?; bookmarks.each { ... }; end # pointless
bookmarks.each { ... } # does the same thing

The general principle: if a method exists that says what you mean, use it instead of reinventing the check with arithmetic. It reads better and communicates intent more clearly.

I’m sure you have similar peeves. I’d love to hear what they are.

These posts are LLM-aided. Backbone, original writing, and structure by Craig. Research and editing by Craig + LLM. Proof-reading by Craig.