DEV Community

B Jacquet
B Jacquet

Posted on

any? and empty? are not antonyms

What I Learned

[nil].any? # => false
Enter fullscreen mode Exit fullscreen mode

Because my expectation was it to be true. My conception of Enumerable#any? was that it returns true if it has any record. Not only that, my metal shortcut it was that was an antonym to Array#empty?.

And why exactly is this interesting?

  1. Ruby has many methods which mean and do the same thing. Like Array#size and Array#length and, to some extent, Enumerable#count.
  2. Ruby has many methods which mean and do opposite things. Like Enumerable#all? and Enumerable#none?
  3. Knowing what empty? does and of 1. and 2., I believed that any? would do its opposite.

Enlightenment came about during code review where I was suggesting to remove the unnecessary if conditional

if collection.any?
  collection.map do |i|

Enter fullscreen mode Exit fullscreen mode

After discussing the problem and poking the code we were able to remove the if by preventing nil from getting into collection.

Top comments (0)