How to copy a ruby variable? How to copy a ruby variable? ruby ruby

How to copy a ruby variable?


foo and bar refer to the same object. To make bar refer to a different object, you have to clone foo:

bar = foo.clone


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 effect foo.


In the below code you can see that foo and bar both are having the same object_id. Thus changing to the foo instance causes same reflection to see through the bar.

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

See here also that I freeze the foo in effect the bar also has been frozen.

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

Thus the right way is below :

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

Cheers!!