← Back to Gists

Safe navigation operator

📝 Ruby
pbuchanan885
pbuchanan885 · Level 10 ·

The safe navigation operator (&.) in Ruby allows you to call a method on an object that may be nil, returning nil instead of raising a NoMethodError.

Ruby
obj = nil
result = obj&.length
puts result # nil obj = "hello"
result = obj&.length
puts result # 5

Comments

1
kwilson kwilson

yeah @brownk1991 i love &. but sometimes it masks a nil i wasn't expecting, making bugs harder to track down, specially in long chains.