Skip to content

Commit 05733e5

Browse files
Nested Collections: "immutable" arrays, Clarify independence of inner arrays in nested collections example (#30215)
* Clarify independence of inner arrays in nested collections example * Rename variable for clarity in immutable nested arrays example * Clarify section heading for creating nested arrays in mutable context * Clarify wording for creating non-mutable nested arrays
1 parent 0335f21 commit 05733e5

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

ruby/basic_ruby/nested_collections.md

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -99,17 +99,19 @@ mutable
9999

100100
Changing the value of the first element in the first nested array, causes the first element to change in all three nested arrays! This same behavior will happen with strings, hashes, or any other mutable objects.
101101

102-
<span id='create-immutable-nested-arrays'>Now, let's take a look at an example that omits the second optional argument and instead passes in the mutable value in a block.</span>
102+
<span id='create-nested-arrays'>Now, let's take a look at an example that omits the second optional argument and instead passes in the mutable value in a block.</span>
103103

104104
```ruby
105-
immutable = Array.new(3) { Array.new(2) }
105+
nested_arrays = Array.new(3) { Array.new(2) }
106106
#=> [[nil, nil], [nil, nil], [nil, nil]]
107-
immutable[0][0] = 1000
107+
nested_arrays[0][0] = 1000
108108
#=> 1000
109-
immutable
109+
nested_arrays
110110
#=> [[1000, nil], [nil, nil], [nil, nil]]
111111
```
112112

113+
Each `{ Array.new(2) }` block creates a new inner array. This means all three inner arrays are **independent objects**. When you modify one, the others stay the same.
114+
113115
Changing the value of the first element in the first nested array does not cause the value to change in any other nested array.
114116

115117
### Adding and removing elements
@@ -352,7 +354,7 @@ The following questions are an opportunity to reflect on key topics in this less
352354
- [How do you add data to a nested hash?](#adding-and-removing-data)
353355
- [How do you delete elements from a nested array?](#remove-elements-nested-array)
354356
- [How do you delete data in a nested hash?](#deleting-data-nested-hash)
355-
- [How do you create a new nested array that is not mutable?](#create-immutable-nested-arrays)
357+
- [How do you create a new nested array that can’t be changed through references to the original one?](#create-nested-arrays)
356358
- [How do you iterate over a nested array?](#iterating-over-a-nested-array)
357359
- [How do you iterate over a nested hash?](#methods)
358360

0 commit comments

Comments
 (0)