Project

General

Profile

Misc #15109 ยป safe_navigation.patch

zverok (Victor Shepelev), 09/12/2018 06:42 PM

View differences:

doc/syntax/calling_methods.rdoc
27 27
receiver but depending on the method's visibility sending a message may raise a
28 28
NoMethodError.
29 29

  
30
You may use <code>&.</code> to designate a receiver, then +my_method+ is not
31
invoked and the result is +nil+ when the receiver is +nil+.  In that case, the
32
arguments of +my_method+ are not evaluated.
33

  
34 30
You may also use <code>::</code> to designate a receiver, but this is rarely
35 31
used due to the potential for confusion with <code>::</code> for namespaces.
36 32

  
33
=== Safe navigation operator
34

  
35
<code>&.</code>, called "safe navigation operator", allows to skip method call
36
when receiver is +nil+. It returns +nil+ and doesn't evaluate method's arguments
37
if the call is skipped.
38

  
39
  REGEX = /(ruby) is (\w+)/i
40
  "Ruby is awesome!".match(REGEX).values_at(1, 2)
41
  # => ["Ruby", "awesome"]
42
  "Python is fascinating!".match(REGEX).values_at(1, 2)
43
  # NoMethodError: undefined method `values_at' for nil:NilClass
44
  "Python is fascinating!".match(REGEX)&.values_at(1, 2)
45
  # => nil
46

  
47
This allows to easily chain methods which could return empty value. Note that
48
<code>&.</code> skips only one next call, so for a longer chain it is necessary
49
to add operator on each level:
50

  
51
  "Python is fascinating!".match(REGEX)&.values_at(1, 2).join(' - ')
52
  # NoMethodError: undefined method `join' for nil:NilClass
53
  "Python is fascinating!".match(REGEX)&.values_at(1, 2)&.join(' - ')
54
  # => nil
55

  
37 56
== Arguments
38 57

  
39 58
There are three types of arguments when sending a message, the positional