↖️ Show all posts

Ruby's Safe Navigation Operator

Ruby 2.3.0 added a safe navigation operator (&.) that checks for nil before calling a method.

It will return nil if str is nil, rather than raising a NoMethodError.

Learned on StackOverflow

str = "   Simon   "
stripper = str&.strip
puts stripper
# => "Simon" 

Somehow what ActiveSupport offers with its try method.

⬅️ Read previous Read next ➡️