How do I handle nil safely in Ruby?

Short answer

Use &. to call a method only when the receiver is not nil, || for a default, and .nil? when you genuinely need to distinguish nil from false.

ruby
user&.address&.city          # nil instead of NoMethodError
name = input || "guest"      # default when nil or false
count ||= 0                  # assign only if currently nil or false

#Only nil and false are falsy

Unlike most languages, 0 and "" are truthy in Ruby:

ruby
puts "yes" if 0     # prints — 0 is truthy
puts "yes" if ""    # prints — "" is truthy

So if value means "not nil and not false", nothing more. Coming from Python or JavaScript, this catches you out in both directions.

#nil? vs empty? vs blank?

ruby
nil.nil?        # true
"".nil?         # false
"".empty?       # true
nil.empty?      # NoMethodError

Calling .empty? on something that might be nil is itself a crash. Either guard it or use the safe navigator:

ruby
if value&.empty?

Rails adds .blank? (nil, false, empty, or whitespace-only) and .present?. They are not in plain Ruby.

#Do not overuse &.

ruby
user&.profile&.settings&.theme

This silences the error but hides which link was missing. If profile should always exist, let it raise — a NoMethodError naming the line beats a nil that surfaces three methods later.

#dig for nested data

ruby
data.dig(:user, :address, :city)     # nil if any level is missing

Works on both hashes and arrays, and reads better than a chain of &..