[前][次][番号順一覧][スレッド一覧]

ruby-changes:53014

From: aycabta <ko1@a...>
Date: Sat, 20 Oct 2018 19:57:38 +0900 (JST)
Subject: [ruby-changes:53014] aycabta:r65228 (trunk): Improve safe navigation operator's docs [Misc #15109]

aycabta	2018-10-20 19:57:33 +0900 (Sat, 20 Oct 2018)

  New Revision: 65228

  https://svn.ruby-lang.org/cgi-bin/viewvc.cgi?view=revision&revision=65228

  Log:
    Improve safe navigation operator's docs [Misc #15109]
    
    * doc/syntax/calling_methods.rdoc: Add Safe navigation operator section.

  Modified files:
    trunk/doc/syntax/calling_methods.rdoc
Index: doc/syntax/calling_methods.rdoc
===================================================================
--- doc/syntax/calling_methods.rdoc	(revision 65227)
+++ doc/syntax/calling_methods.rdoc	(revision 65228)
@@ -27,13 +27,32 @@ This sends the +my_method+ message to +m https://github.com/ruby/ruby/blob/trunk/doc/syntax/calling_methods.rdoc#L27
 receiver but depending on the method's visibility sending a message may raise a
 NoMethodError.
 
-You may use <code>&.</code> 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 <code>::</code> to designate a receiver, but this is rarely
 used due to the potential for confusion with <code>::</code> for namespaces.
 
+=== Safe navigation operator
+
+<code>&.</code>, 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
+<code>&.</code> 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

--
ML: ruby-changes@q...
Info: http://www.atdot.net/~ko1/quickml/

[前][次][番号順一覧][スレッド一覧]