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:
defcomplex_valuething=some_query{status: (thing?:ok::not_found),content: thing.something}# always responds to [:status] and [:content]end
B) Return an object with a NullObject pattern to avoid nil.something down the line.
classResultattr_reader:name,:otherdefinitialize(value)@name=value?value.name:'Not found'@price=value?" $#{value.amount} ":'-'endenddefcomplex_valuething=some_queryResult.new(thing)# always responds to '.name' and '.price'end
I know the example is a bit contrived due to brevity, but I hope it lets my point though.
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! 😁
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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:
B) Return an object with a NullObject pattern to avoid
nil.something
down the line.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
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! 😁