If Ruby method returns null or empty object
I take my first shot at writing a core library by learning Ruby and running into a little hurdle.
What is a Ruby-esque method for handling return values for methods returning iterations? Should the method return an empty hash / array / or Nil?
I am trying to keep potential users of my library in how they will handle any case in their code.
EDIT: I think I would like to return an empty object, because if they iterate over the return value with .each for example, it will at least terminate and not blow up NoMethodError on NilClass.
source to share
I don't think you are asking the right question. Take a look at Ruby's built-in methods. Many will return a collection that may be empty, but something else needs to be returned in certain situations. This is something else often nil
, but not always.
To begin with, there are many "bang" methods that return a (possibly empty) collection if a change is made in the receiver, 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!
.
Several other methods return a (possibly empty) collection or nil
when the 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 the object to a (possibly empty) hash if it can and returns nil
if it cannot.
And it's not just an empty collection against nil
. Some Ruby methods return a collection or something besides nil
. This includes many methods that return a collection when a block is passed, but return an enumerator if the block is not present (to provide chaining of enumerations).
My advice is not to try to decide if it will always be an empty collection or always nil
. Read the Ruby built-in techniques documentation to see what some very smart and experienced Rubyists have done, then go through them on a case-by-case basis with some guidelines.
source to share