Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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.

like image 629
Nathan Long Avatar asked Sep 23 '09 12:09

Nathan Long


People also ask

What is shallow copy Ruby?

Shallow copyIf a variable of the copied object is a reference to another object, then just the reference address of the object is copied.

How do you copy a string in Ruby?

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.

What is DUP in Ruby?

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.

How do you copy variables?

This is done by selecting the variables in the Variables and Questions tab, right-clicking and selecting Copy and Paste Variable(s) > Exact Copy.


1 Answers

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") 
like image 190
khelll Avatar answered Sep 22 '22 14:09

khelll