Be Cool with Arrays
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.**
```ruby
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.**
```ruby
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.**
```ruby
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.
Questions or thoughts? Get in touch.