I don't think you're asking the right question. Take a look at Ruby's built-in methods. Many return a collection, which may be empty, but also have a need to return something else in certain situations. That something else is often nil
, but not always.
To start, there are many "bang" methods that return a (possibly-empty) collection if a change to the receiver is made, but return nil
when no change is made. Examples include Array#compact!
, Array#flatten!
, Array#reject!
, Array#select!
, Array#uniq!
, Hash#reject!
and Hash#select!
.
Some other methods return a (possibly-empty) collection or nil
when an operation cannot be performed. For example, Array#slice
and Array#slice!
return nil
if the first index is out-of-range; Hash::try_convert
converts an object to a (possibly-empty) hash if it can, and returns nil
if it cannot.
And it's not just an empty collection versus nil
. Some Ruby methods return a collection or something else other than nil
. That includes many, many methods that return a collection when passed a block but return an enumerator if no block is present (to permit the chaining of enumerators).
My advice is not to try to decide whether it will always be an empty collection or always nil
. Read through the documentation of Ruby's built-in methods to see what some very smart and experienced Rubyists have done, and then deal with it on a case-by-case basis, with some guiding principles.