If you’ve been programming in Ruby for any amount of time, you’ve probably seen an error like this:
The meaning is actually pretty straightforward if you think about it. There’s a
method called “methodname” and it’s not defined for an object with the value of
nil and a class of
NilClass. Try it:
nil isn’t special here, other classes do throw the same error:
We’re only really focusing on the case where an undefined method is called on
nil though. I just thought it was important to point out.
Anyways, probably the most common method you’ll see this happen with is:
Generally this happens when you’re pulling data out of a nested data structure you receive over HTTP or some other protocol:
In the above code, we assumed that every response would have a nested array as
the third element of the outer array. Of course, this was not the case for
response3. There is no third element in
nil is returned. We
then try to run the
 method on that
nil and that’s when we generate the
Let’s fix it:
Thoughts for the reader:
- Is there a better way to handle this?
- Where else might you run into errors like this?