Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions ruby/basic_ruby/nested_collections.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,17 +99,19 @@ mutable

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.

<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>
<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>

```ruby
immutable = Array.new(3) { Array.new(2) }
nested_arrays = Array.new(3) { Array.new(2) }
#=> [[nil, nil], [nil, nil], [nil, nil]]
immutable[0][0] = 1000
nested_arrays[0][0] = 1000
#=> 1000
immutable
nested_arrays
#=> [[1000, nil], [nil, nil], [nil, nil]]
```

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.

Changing the value of the first element in the first nested array does not cause the value to change in any other nested array.

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

Expand Down