Quick Answer
Common error when calling methods on nil values.
Understanding the Issue
This occurs when a variable is nil and you try to call a method on it. Always check for nil or use safe navigation.
The Problem
This code demonstrates the issue:
Ruby
Error
# Problem: Nil reference
user = find_user(id)
user.name # Error if user is nil
The Solution
Here's the corrected code:
Ruby
Fixed
# Solution 1: Check nil
user.name if user
# Solution 2: Safe navigation (Ruby 2.3+)
user&.name
# Solution 3: Null object pattern
class NullUser
def name
"Guest"
end
end
user || NullUser.new
Key Takeaways
Always handle nil cases defensively.