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

In Ruby, how can I copy a variable so that changes in the original do not 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, two variables point to the same object; I want to create a new object for the second variable, but must first contain the same information.

+45
ruby
Sep 23 '09 at 12:05
source share
3 answers

As for copying, you can do:

 phrase2 = phrase1.dup 

or

 # Clone: copies singleton methods as well phrase2 = phrase1.clone 

You can do this to avoid copying at all:

 phrase2 = phrase1.gsub("Hello","Hi") 
+77
Sep 23 '09 at 12:27
source share

Using your example, instead of:

 phrase2 = phrase1 

Try:

 phrase2 = phrase1.dup 
+16
Sep 23 '09 at 12:11
source share
 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" 
0
Jul 14 '14 at 8:23
source share



All Articles