Home
Ruby
Array Copy Example
Updated Nov 12, 2021
Dot Net Perls
Copy array. An array is stored in a region of memory. When we modify it, we modify that region of memory. Two array variables can point to the same region.
Ruby syntax note. We can copy an array, with slice syntax, to create separate arrays. This can be helpful in recursive methods.
Array
Recursion
Example. First, this program slices an array with the square-bracket syntax. It specifies a slice on "values" from 0 to values.length. This is a total-array slice.
Info After the slice, "values" and "copy" point to separate memory regions. We test that our arrays are separate.
Detail We modify the copied array, and the original array is not changed. An array copy was made.
# 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"
VALUES: ["cat", "dog", "mouse"] COPY: ["snail", "dog", "mouse"] VALUES: ["cat", "dog", "mouse"]
Example 2. This example is similar, but has one difference. It specifies the length of the slice with a final index of negative one. This means the last index.
Tip This syntax form is not better (or worse) than the previous one. It comes down to what syntax form you prefer.
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"
[1, 10, 100] [1000, 10, 100]
Slice. The slice method is an alias for the square-bracket slicing syntax. So calling slice with the same arguments yields an equivalent result.
Method
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"
[8, 9, 10] [5, 9, 10]
Summary. An array copy is sometimes needed. If you do not copy an array, the original array will be modified. And once modified, you might not be able to retrieve the original values.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Nov 12, 2021 (image).
Home
Changes
© 2007-2025 Sam Allen