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

Ruby

Ruby Problem Overview


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.

Ruby Solutions


Solution 1 - Ruby

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

Solution 2 - Ruby

Using your example, instead of:

phrase2 = phrase1

Try:

phrase2 = phrase1.dup

Solution 3 - Ruby

phrase1 = "Hello Jim"
   # => "Hello Jim"

phrase2 = Marshal.load(Marshal.dump(phrase1))
   # => "Hello Jim"

phrase1.gsub!("Hello","Hi")
   #  => "Hi Jim" 

puts phrase2
   # "Hello Jim"

puts phrase1
   # "Hi Jim"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNathan LongView Question on Stackoverflow
Solution 1 - RubykhelllView Answer on Stackoverflow
Solution 2 - RubyJacob WinnView Answer on Stackoverflow
Solution 3 - RubyRafeeqView Answer on Stackoverflow