tags:

views:

163

answers:

2

In Ruby, how can I copy a variable such that changes to the copy don't affect the original?

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.

+5  A: 

Using your example, instead of:

phrase2 = phrase1

Try:

phrase2 = phrase1.dup
Jacob Winn
Your answer works for the question I asked, which was pretty general. It doesn't seem to work for the problem I'm really trying to solve, though, which is here: http://stackoverflow.com/questions/1465696/ruby-how-can-i-copy-this-global-variable. Any ideas?
Nathan Long
Thanks for your help, by the way. :)
Nathan Long
+2  A: 

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")
khelll