Recently, I was working on some Ruby code where I had to check if an array is empty. It turns out there are many ways to skin this cat. Here I’ll document my learnings…
irb(main):001:0> !! => true
As such, doing something like this won’t work…
if some_array do_something # More code... end
One option that does work is to check the length of the array…
irb(main):001:0> .length => 0 irb(main):002:0> .length => 1 irb(main):003:0> [1, 'foo'].length => 2
As such the following will work if you want to do something if the array has elements…
if some_array.length > 0 do_something # More code.. end
On a pull request I was working on I started out checking the length, however when I ran Rubocop I saw it didn’t like that…
$ rubocop Inspecting 1 file C Offenses: test.rb:2:4: C: Use !empty? instead of length > 0. if some_array.length > 0 ^^^^^^^^^^^^^^^^^^^^^
Aha! So a cleaner approach is call the
empty? method on the array…
irb(main):001:0> .empty? => true irb(main):002:0> ['foo'].empty? => false
Now we can rewrite our code as…
if !some_array.empty? do_something # More code end
Rubocop is still not happy…
$ ruby Inspecting 1 file C Offenses: test.rb:2:1: C: Favor unless over if for negative conditions. if !some_array.empty? ... ^^^^^^^^^^^^^^^^^^^^^
It would like us to switch from
if ! to
unless. In my use case, however,
unless wouldn’t work because I was checking two conditions.
if some_condition && !some_array.empty? do_something # More code end
However another alternative, I subsequently learned is to use
if some_condition && some_array.any? do_something # More code end
One important thing to note about
any? is documented in the Stack Overflow questions “Check for array not empty: any?”
any? will return
false array that contains only
irb(main):009:0> [nil].any? => false
!empty? will return true…
irb(main):011:0> ![nil].empty? => true
Hi, I'm Max!
I'm a software developer who mainly works in PHP, but also dabbles in Ruby and Go. Technical topics that interest me are monitoring, security and performance.
During the day I solve challenging technical problems at Something Digital where I mainly work with the Magento platform. I also blog about tech, work on open source and hunt for bugs.
If you'd like to get in touch with me the best way is on Twitter.