RUBY / CHAPTER 05

Array copies and nested state

Intermediate

Make the depth of independence part of the collection contract.

By the end of this chapter

  • Trace aliases and shallow duplication
  • Remove elements without skipping candidates
  • Preserve duplicates and input order

The idea

An Array stores references to its elements. Assigning it to another variable shares the array, while dup creates a new outer array containing the same element references. Replacing an outer position in the duplicate is independent, but mutating a shared nested array or string can affect both views. Choose a copying strategy from the structure you actually need to isolate.

Filtering into a new result often communicates intent more clearly than deleting while traversing indices. Removing an element shifts later positions, which can make a forward loop skip adjacent matches. If mutation is required, use an appropriate collection operation or a carefully designed reverse traversal. A stable filter keeps the relative order and repeated occurrences of retained values; converting through a set would change that contract.

Ruby example
a=[[1],[2]]
b=a.dup
b[0] << 9
b[1]=[8]
p a
p b
Result
[[1, 9], [2]]
[[1, 9], [8]]

The first nested array remains shared, but replacing b’s second position changes only the copied outer array.

Try it yourself

Build three independent empty rows and verify that appending to one leaves the others unchanged.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which creates three independent empty arrays?