To copy an array in Ruby, you can use the clone method or the dup method.
In this example,
arr1
with elements.clone
method to create a copy of arr1
into arr2
.clone
method creates a shallow copy of the array.arr1 = [1, 2, 3, 4, 5]
arr2 = arr1.clone
puts "Array 1: #{arr1}"
puts "Array 2 (copy of Array 1): #{arr2}"
Array 1: [1, 2, 3, 4, 5] Array 2 (copy of Array 1): [1, 2, 3, 4, 5]
In this example,
arr1
with elements.dup
method to create a copy of arr1
into arr2
.dup
method also creates a shallow copy of the array.arr1 = [1, 2, 3, 4, 5]
arr2 = arr1.dup
puts "Array 1: #{arr1}"
puts "Array 2 (copy of Array 1): #{arr2}"
Array 1: [1, 2, 3, 4, 5] Array 2 (copy of Array 1): [1, 2, 3, 4, 5]
In this tutorial, we learned How to Copy an Array in Ruby language with well detailed examples.