In Ruby, how can I copy a variable such that changes to the original don't affect the copy?
For example:
phrase1 = "Hello Jim" phrase2 = phrase1 phrase1.gsub!("Hello","Hi") p phrase2 #outputs "Hi Jim" - I want it to remain "Hello Jim"
In this example, the two variables point to the same object; I want to create a new object for the second variable but have it contain the same information initially.
Shallow copyIf a variable of the copied object is a reference to another object, then just the reference address of the object is copied.
We can use the asterisk * operator to duplicate a string for the specified number of times. The asterisk operator returns a new string that contains a number of copies of the original string.
According to Ruby-doc, both #clone and #dup can be used to create a shallow copy of an object, which only traverse one layer of complexity, meaning that the instance variables of obj are copied, but not the objects they reference. They would all share the same attributes; modifying one would result a change on another.
This is done by selecting the variables in the Variables and Questions tab, right-clicking and selecting Copy and Paste Variable(s) > Exact Copy.
As for copying you can do:
phrase2 = phrase1.dup
or
# Clone: copies singleton methods as well phrase2 = phrase1.clone
You can do this as well to avoid copying at all:
phrase2 = phrase1.gsub("Hello","Hi")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With