How to copy ruby ​​variable?

I may have looked at my screen for too long today, but something that, in my opinion, should be very simple, challenges me.

I am trying to create a “copy” of a variable so that I can manipulate it without changing the original.

# original var is set foo = ["a","b","c"] # i want a copy of the original var so i dont modify the original bar = foo # modify the copied var bar.delete("b") # output the values puts bar # outputs: ["a","c"] - this is right puts foo # outputs: ["a","c"] - why is this also getting modified? 

I want foo not to change.

+7
source share
3 answers

foo and bar refer to the same object. To make bar reference to another object, you must clone foo :

 bar = foo.clone 
+11
source

You can use the dup method:

 bar = foo.dup 

This will return a copy of foo, so any changes you make to bar will not affect foo.

+4
source

In the code below, you can see that foo and bar both have the same object_id . Thus, going to the foo instance causes the same reflection as through bar .

 foo = ["a","b","c"] #=> ["a", "b", "c"] foo.object_id #=> 16653048 bar = foo #=> ["a", "b", "c"] bar.object_id #=> 16653048 bar.delete("b") #=> "b" puts bar #a #c #=> nil puts foo #a #c #=> nil 

See also that I freeze foo , as a result the bar was also frozen.

 foo.freeze #=> ["a", "c"] foo.frozen? #=> true bar.frozen? #=> true 

So the correct way below:

 bar = foo.dup #=> ["a", "b", "c"] foo.object_id #=> 16450548 bar.object_id #=> 16765512 bar.delete("b") #=> "b" print bar #["a", "c"]=> nil print foo #["a", "b", "c"]=> nil 

Hooray!!

+3
source

All Articles