How do I handle nil safely in Ruby?
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.
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:
puts "yes" if 0 # prints — 0 is truthy
puts "yes" if "" # prints — "" is truthySo 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?
nil.nil? # true
"".nil? # false
"".empty? # true
nil.empty? # NoMethodErrorCalling .empty? on something that might be nil is itself a crash. Either guard it or use the safe navigator:
if value&.empty?Rails adds .blank? (nil, false, empty, or whitespace-only) and .present?. They are not in plain Ruby.
#Do not overuse &.
user&.profile&.settings&.themeThis 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
data.dig(:user, :address, :city) # nil if any level is missingWorks on both hashes and arrays, and reads better than a chain of &..