The Ampersand Dot Operator in Ruby
May 3, 2018
Ruby allows you to write code like this:
name = nil
=> nil
name&.length
=> nilThis is called the Safe Navigation Operator and was introduced in Ruby 2.3 - it’s similar to the try method in Rails, but it’s faster.
Today I learnt that this can be combined with other operators, for example:
price = nil
=> nil
taxes = 0.99
=> 0.99
price&. + taxes
=> nilIt definitely looks strange to me, but it’s useful in certain contexts.
An interesting bit of history is that many other programming languages (Objective C, Python, Swift, Scala, CoffeeScript) have a similar feature but use a question mark instead of an ampersand - ?.. However, methods in Ruby can contain a question mark so ?. is already valid syntax, so the Ruby community had to use a different syntax.