How to copy a ruby variable?
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!!