Chapter 8 - References

Exercise 1: Softball team

Joe Walsh is having a bad day. He couldn’t convince the newest employee, Lisa Wagner, to join the company softball team, so he had to draft the team mascot to play for tonight’s game instead. And now his program to print the company roster is broken.

Here’s the problem: Joe thought he was copying the array in the staff variable to the softball_team variable. But actually, he just copied a reference to the array - he aliased it. So when he added elements to staff and softball_team, they both ended up on the same array!

staff = ["Walsh", "Moreno", "Nash", "Cox",
         "Rios", "Jones", "Gupta", "Hayes"]
softball_team = staff # Aliases the same variable!

# Adds an element to the array...
staff << "Wagner"
# Adds an element to the SAME array!
softball_team << "Zonky the Wonder Squirrel" 

puts "Company staff:", staff
print "\n\n"
puts "Company softball team:", softball_team

So the output doesn’t show the contents of two different arrays; it just prints the same array, twice!

Company staff:
Walsh
Moreno
Nash
Cox
Rios
Jones
Gupta
Hayes
Wagner
Zonky the Wonder Squirrel


Company softball team:
Walsh
Moreno
Nash
Cox
Rios
Jones
Gupta
Hayes
Wagner
Zonky the Wonder Squirrel

One way to fix this would be to create two separate arrays; to basically copy and paste the array literal.

staff = ["Walsh", "Moreno", "Nash", "Cox",
         "Rios", "Jones", "Gupta", "Hayes"]
softball_team = ["Walsh", "Moreno", "Nash", "Cox",
                 "Rios", "Jones", "Gupta", "Hayes"]

# Adds an element to the first array...
staff << "Wagner"
# Adds an element to the second array.
softball_team << "Zonky the Wonder Squirrel" 

puts "Company staff:", staff
print "\n\n"
puts "Company softball team:", softball_team

But there’s another way you should know about (that we didn’t cover in the book); the clone method. When you call clone on an Array object, you get a copy of that array back. You can modify that array as much as you want, and it won’t affect the original array. (That is, you can modify the array as much as you want. But be careful! The array still holds aliases to the same objects, so if you modify those, the change will be visible in both arrays!)

staff = ["Walsh", "Moreno", "Nash", "Cox",
         "Rios", "Jones", "Gupta", "Hayes"]
softball_team = staff.clone

# Adds an element to the first array...
staff << "Wagner"
# Adds an element to the cloned array.
softball_team << "Zonky the Wonder Squirrel" 

puts "Company staff:", staff
print "\n\n"
puts "Company softball team:", softball_team

Both of these programs produce the correct output:

Company staff:
Walsh
Moreno
Nash
Cox
Rios
Jones
Gupta
Hayes
Wagner


Company softball team:
Walsh
Moreno
Nash
Cox
Rios
Jones
Gupta
Hayes
Zonky the Wonder Squirrel