Reputation: 195
I am taking my first shot at writing a basic library while learning Ruby and have come to a small hurdle.
What is the Ruby-esque way of handling return values for methods that return iterables? Should a method return an empty hash/array/ or Nil?
I am trying to keep the potential users of my library in mind in how they would handle either case in their code.
EDIT: I think I would like to return an empty object because then if they are iterating over the return value with a .each, for example, it would at least complete and not blow up with a NoMethodError on NilClass.
Upvotes: 4
Views: 4683
Reputation: 110725
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.
Upvotes: 4
Reputation: 54
Not only in ruby but also in other languages, you should return an empty enumerable/collection. There is no need for your users to check if the return value is nil or not before doing any action, it's a waste of time.
Upvotes: 3