3

Below is an example of named arguments in Ruby, but what does the ampersand do?

def set_tools(foo:, bar:, baz:)
    @instance_variable = baz&.stuff
mangocaptain1
  • 515
  • 1
  • 6
  • 12

1 Answers1

8

It is called as Safe Navigation Operator. Introduced in ruby 2.3.0

You can use it to make sure the value exist before calling some method on it

For example:

a = nil

a.some_method # This will break

#=> NoMethodError: undefined method `some_method' for nil:NilClass

a&.some_method # This will not

#=> nil

You can use this operator instead of

a && a.some_method && a.some_method.some_other_method
# OR
a.try(:some_method).try(:some_other_method)

Using this operator

a&.some_method&.some_other_method
Deepak Mahakale
  • 22,834
  • 10
  • 68
  • 88