C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: We test that our arrays are separate. We modify the copied array, and the original array is not changed.
Ruby program that copies array
# Create an array.
values = ["cat", "dog", "mouse"]
print "VALUES: ", values, "\n"
# Copy the array using a total-array slice.
# ... Modify the new array.
copy = values[0 .. values.length]
copy[0] = "snail"
print "COPY: ", copy, "\n"
# The original array was not modified.
print "VALUES: ", values, "\n"
Output
VALUES: ["cat", "dog", "mouse"]
COPY: ["snail", "dog", "mouse"]
VALUES: ["cat", "dog", "mouse"]
Tip: This syntax form is not better (or worse) than the previous one. It comes down to what syntax form you prefer.
Ruby program that copies array with negative one
values = [1, 10, 100]
# Copy the array with a different syntax.
copy = values[0 .. -1]
copy[0] = 1000
# Display the arrays.
print values, "\n"
print copy, "\n"
Output
[1, 10, 100]
[1000, 10, 100]
Opinion: For an experienced developer using Ruby, a total-array slice is easy to understand.
Ruby program that uses slice, copies array
values = [8, 9, 10]
# Use slice method to copy array.
copy = values.slice(0 .. -1)
copy[0] = 5
# Display two arrays.
print values, "\n"
print copy, "\n"
Output
[8, 9, 10]
[5, 9, 10]