From ecc627b20aa011616d29a765448957c445be7a62 Mon Sep 17 00:00:00 2001 From: aycabta Date: Sat, 20 Oct 2018 10:57:33 +0000 Subject: Improve safe navigation operator's docs [Misc #15109] * doc/syntax/calling_methods.rdoc: Add Safe navigation operator section. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@65228 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- doc/syntax/calling_methods.rdoc | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/doc/syntax/calling_methods.rdoc b/doc/syntax/calling_methods.rdoc index ec86ef05ee..b86d60ad88 100644 --- a/doc/syntax/calling_methods.rdoc +++ b/doc/syntax/calling_methods.rdoc @@ -27,13 +27,32 @@ This sends the +my_method+ message to +my_object+. Any object can be a receiver but depending on the method's visibility sending a message may raise a NoMethodError. -You may use &. to designate a receiver, then +my_method+ is not -invoked and the result is +nil+ when the receiver is +nil+. In that case, the -arguments of +my_method+ are not evaluated. - You may also use :: to designate a receiver, but this is rarely used due to the potential for confusion with :: for namespaces. +=== Safe navigation operator + +&., called "safe navigation operator", allows to skip method call +when receiver is +nil+. It returns +nil+ and doesn't evaluate method's arguments +if the call is skipped. + + REGEX = /(ruby) is (\w+)/i + "Ruby is awesome!".match(REGEX).values_at(1, 2) + # => ["Ruby", "awesome"] + "Python is fascinating!".match(REGEX).values_at(1, 2) + # NoMethodError: undefined method `values_at' for nil:NilClass + "Python is fascinating!".match(REGEX)&.values_at(1, 2) + # => nil + +This allows to easily chain methods which could return empty value. Note that +&. skips only one next call, so for a longer chain it is necessary +to add operator on each level: + + "Python is fascinating!".match(REGEX)&.values_at(1, 2).join(' - ') + # NoMethodError: undefined method `join' for nil:NilClass + "Python is fascinating!".match(REGEX)&.values_at(1, 2)&.join(' - ') + # => nil + == Arguments There are three types of arguments when sending a message, the positional -- cgit v1.2.3