Ruby: how can I copy a variable without pointing to the same object?

Viewed 45327

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.

3 Answers
Related