ruby.onl / secret-operators

Safe Navigation and Inline Rescue: Never Crash on nil Again

2026-02-27

Ruby 2.3 added the &. operator (safe navigation), which returns nil instead of exploding when you call a method on nil. Combined with inline rescue, you can write bulletproof data access chains that gracefully handle missing values. No more "undefined method for nil:NilClass" at 3 AM.

Part 1: Safe Navigation Operator (&.)

# Without safe navigation: if user && user.name puts user.name end # With safe navigation: puts user&.name # nil if user is nil, else user.name # Chaining: user&.address&.city&.upcase # nil if any step is nil
Perl equivalent: $user && $user->name (manual chaining). Ruby's &. does it in one operator.

With Regex

# Safe regex capture - won't explode on nil line&.match(%r~(\d+)~)&.[](1) # If line is nil, returns nil instead of crashing

In Assignments

# Safe method call in assignment city = user&.profile&.address&.city || "Unknown"

Part 2: The Gotcha

&. only protects against nil, not against missing methods:
"hello"&.nonexistent_method # NoMethodError! (string isn't nil) nil&.nonexistent_method # nil (nil is caught)
It's a nil guard, not a universal error suppressor.

Part 3: Inline Rescue

Single-line rescue for quick error handling. Catches any exception and returns a default value.
# Safe parsing with default count = Integer(input) rescue 0 # Safe file reading content = File.read(path) rescue "" # Safe hash/array access name = data[:users].first[:name] rescue "N/A" # Safe method call result = risky_operation rescue "failed"
Perl equivalent: eval { ... } or do { ... } but way more concise.

Part 4: Warning About Inline Rescue

This catches ALL StandardError exceptions, which can hide bugs:
# This hides the real error: value = broken_code rescue "default" # Better: be specific in full rescue blocks begin value = broken_code rescue ArgumentError value = "default" end
Use inline rescue sparingly and only when you genuinely want to ignore any error. It's a convenience tool, not a safety net for sloppy code.

Part 5: Combining Both

# Safe navigation + inline rescue for maximum safety port = config&.dig(:database, :port) rescue 5432 # Chain with fallback name = user&.profile&.display_name || user&.email || "anonymous"

Part 6: When to Use Which

Situation Use
Might be nil &. safe navigation
Might raise exception rescue inline
Might be nil OR raise Combine both
Need specific error handling Full begin/rescue/end block
Simple default value || with fallback
Pick the lightest tool that handles your case. &. for nil chains, rescue for exception-prone operations, || for simple defaults.

Created By: Wildcard Wizard. Copyright 2026