You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
Copy file name to clipboardExpand all lines: ruby/basic_ruby/nested_collections.md
+7-5Lines changed: 7 additions & 5 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -99,17 +99,19 @@ mutable
99
99
100
100
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.
101
101
102
-
<spanid='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
+
<spanid='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>
103
103
104
104
```ruby
105
-
immutable=Array.new(3) { Array.new(2) }
105
+
nested_arrays=Array.new(3) { Array.new(2) }
106
106
#=> [[nil, nil], [nil, nil], [nil, nil]]
107
-
immutable[0][0] =1000
107
+
nested_arrays[0][0] =1000
108
108
#=> 1000
109
-
immutable
109
+
nested_arrays
110
110
#=> [[1000, nil], [nil, nil], [nil, nil]]
111
111
```
112
112
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
+
113
115
Changing the value of the first element in the first nested array does not cause the value to change in any other nested array.
114
116
115
117
### Adding and removing elements
@@ -352,7 +354,7 @@ The following questions are an opportunity to reflect on key topics in this less
352
354
-[How do you add data to a nested hash?](#adding-and-removing-data)
353
355
-[How do you delete elements from a nested array?](#remove-elements-nested-array)
354
356
-[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)
356
358
-[How do you iterate over a nested array?](#iterating-over-a-nested-array)
357
359
-[How do you iterate over a nested hash?](#methods)
0 commit comments