DEV Community

Discussion on: How to return multiple values in ruby

Collapse
 
oinak profile image
Oinak • Edited

That is a very neat explanation, thanks for sharing!

I see your post is centered on the how and not on the why.

One of the most common errors in ruby is:

NoMethodError: undefined method 'foo' for nil:NilClass

It comes from calling a method on the result of a function that we forgot could return nil.

Usually, when I feel tempted to return mutiple or complex values, I tend to:

A) Return a hash than documents what they are:

  def complex_value
    thing = some_query
    {
      status: (thing ? :ok : :not_found),
      content: thing.something
    } # always responds to [:status] and [:content]
  end
Enter fullscreen mode Exit fullscreen mode

B) Return an object with a NullObject pattern to avoid nil.something down the line.

class Result
  attr_reader :name, :other
  def initialize(value)
    @name = value ? value.name : 'Not found'
    @price = value ? " $#{value.amount} " : '-'
  end
end

def complex_value
  thing = some_query
  Result.new(thing) # always responds to '.name' and '.price'
end
Enter fullscreen mode Exit fullscreen mode

I know the example is a bit contrived due to brevity, but I hope it lets my point though.

What do you think?

P.S.: Sandi Metz on this matters

Collapse
 
viricruz profile image
ViriCruz

Yes, you're right NoMethodError: undefined method 'foo' for nil:NilClass this a very common error in ruby and I understand your point of view. Thanks for sharing your opinions! 😁