← Back to Error Lab

Ruby: NoMethodError: undefined method for nil:NilClass

Published 2026-04-21

Educational use only. Content explains errors and defensive fixes for systems you own or are authorised to test. Do not use any technique here to access data, accounts, or networks without permission.

Root Cause

This is Ruby's equivalent of the NullPointerException. It occurs when you call a method on a variable that evaluates to `nil`. In Ruby, everything is an object, including `nil` (which is the singular instance of `NilClass`). If an Active Record query returns nothing (`User.find_by(name: 'Ghost')`), it returns `nil`. Attempting to call `.email` on that result tries to find an `email` method on `NilClass`, which doesn't exist, leading to a crash.

Fix / Solution

Implement defensive checks before calling methods on potentially nil objects. The most elegant modern Ruby solution is using the safe navigation operator (`&.`), which will return `nil` instead of crashing if the object is `nil`. Alternatively, use Active Record methods that raise specific exceptions when records aren't found (like `find` or `find_by!`) so you can rescue them explicitly.

Code Snippet

# ❌ Crashes if user is not found
user = User.find_by(email: 'missing@test.com')
puts user.name

# ✅ Fix 1: Safe navigation operator
puts user&.name

# ✅ Fix 2: Explicit conditional
if user
  puts user.name
end