diff options
author | Burdette Lamar <[email protected]> | 2020-05-15 16:12:40 -0500 |
---|---|---|
committer | GitHub <[email protected]> | 2020-05-15 14:12:40 -0700 |
commit | 24739c62e5cee1eaa0857fee2800c8bcba8c9ced (patch) | |
tree | a3df383978a2f38d001c3a64917d1fd8b95a1134 /doc/syntax/calling_methods.rdoc | |
parent | a3cd01524c7295da87e2dd013d92f289cfe5b635 (diff) |
[ci skip] Rdoc enhancements for Array (#3063)
* Per @nobu review
* Rdoc enhancements for Array
* Responses to review
Notes
Notes:
Merged-By: drbrain <[email protected]>
Diffstat (limited to 'doc/syntax/calling_methods.rdoc')
-rw-r--r-- | doc/syntax/calling_methods.rdoc | 36 |
1 files changed, 35 insertions, 1 deletions
diff --git a/doc/syntax/calling_methods.rdoc b/doc/syntax/calling_methods.rdoc index 5abecc69da..fc806d5c31 100644 --- a/doc/syntax/calling_methods.rdoc +++ b/doc/syntax/calling_methods.rdoc @@ -30,7 +30,41 @@ NoMethodError. 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 +=== Chaining \Method Calls + +You can "chain" method calls by immediately following one method call with another. + +This example chains methods Array#append and Array#compact: + + a = [:foo, 'bar', 2] + a1 = [:baz, nil, :bam, nil] + a2 = a.append(*a1).compact + a2 # => [:foo, "bar", 2, :baz, :bam] + +Details: + +- First method <tt>merge</tt> creates a copy of <tt>a</tt>, + appends (separately) each element of <tt>a1</tt> to the copy, and returns + [:foo, "bar", 2, :baz, nil, :bam, nil] +- Chained method <tt>compact</tt> creates a copy of that return value, + removes its <tt>nil</tt>-valued entries, and returns + [:foo, "bar", 2, :baz, :bam] + +You can chain methods that are in different classes. +This example chains methods Hash#to_a and Array#reverse: + + h = {foo: 0, bar: 1, baz: 2} + h.to_a.reverse # => [[:baz, 2], [:bar, 1], [:foo, 0]] + +Details: + +- First method Hash#to_a converts <tt>a</tt> to an \Array, and returns + [[:foo, 0], [:bar, 1], [:baz, 2]] +- Chained method Array#reverse creates copy of that return value, + reverses it, and returns + [[:baz, 2], [:bar, 1], [:foo, 0]] + +=== 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 |