InQusitive - 13 days ago 6
Ruby Question

Use of = vs .dup method

``````array = [1,2,3,4,5]

array1 = array
array2 = array.dup

puts array1 == array2
``````

Why do we have a
`dup`
method when we can just asign to another variable?

A statement like:

``````array1 = array
``````

just assigns a reference to `array1` from `array`. This means that both `array` and `array1` point to the same memory location. If you change the underlying array, it will be reflected in both copies:

``````irb(main):001:0> array = [1,2,3]
=> [1, 2, 3]
irb(main):002:0> array1 = array
=> [1, 2, 3]
irb(main):003:0> array
=> [1, 2, 3]
irb(main):004:0> array1
=> [1, 2, 3]
irb(main):005:0> array[0] = 10
=> 10
irb(main):006:0> array
=> [10, 2, 3]
irb(main):007:0> array1
=> [10, 2, 3]
``````

If you use `dup`, it clones the underlying data, creating new, independent storage:

``````irb(main):008:0> array2 = array.dup
=> [10, 2, 3]
irb(main):009:0> array
=> [10, 2, 3]
irb(main):010:0> array2
=> [10, 2, 3]
irb(main):011:0> array2[0] = 20
=> 20
irb(main):012:0> array
=> [10, 2, 3]
irb(main):013:0> array2
=> [20, 2, 3]
``````
Source (Stackoverflow)