This can be solve by using a.collect or a.dup but the problem would
occur again if a,b are multi dimensions Array. dup or collect reference
on the sub-Array?
Isn’t there a clean and consise way to copy the whole content of an
multi dimension Array so that the copy is not somehow linked to the
original.
Btw, a would be modified even though it is accessed as attri_reader. So
I guess = is copying the pointer rather than any content (a.id == b.id)
The = operator seems to retrieve an reference on a Array rather than
copying what it contains
as in the following code:
a = [1,2,3]
b = a
p b.id; p a.id
b.each_index do |i|
b[i] *= 2
end
both a and b equals to [2,4,6]
This can be solve by using a.collect or a.dup but the problem would
occur again if a,b are multi dimensions Array. dup or collect reference
on the sub-Array?
Isn’t there a clean and consise way to copy the whole content of an
multi dimension Array so that the copy is not somehow linked to the
original.
Btw, a would be modified even though it is accessed as attri_reader. So
I guess = is copying the pointer rather than any content (a.id ==
b.id)
The = operator seems to retrieve an reference on a Array rather than
copying what it contains
as in the following code:
*******
a = [1,2,3]
b = a
p b.id; p a.id
b.each_index do |i|
b[i] *= 2
end
********
both a and b equals to [2,4,6]
This can be solve by using a.collect or a.dup but the problem would
occur again if a,b are multi dimensions Array. dup or collect reference
on the sub-Array?
Isn't there a clean and consise way to copy the whole content of an
multi dimension Array so that the copy is not somehow linked to the
original.
Use Marshal:
def deep_clone(anObj)
Marshal.load(Marshal.dump(anObj))
end
Btw, a would be modified even though it is accessed as attri_reader.
You can modify the arrays content, but you cannot assign a new object to
a (@a).
So I guess = is copying the pointer rather than any content (a.id == b.id)
= is just a reference assignment, does not copy anything except the
pointer at all.
Note that = or obj.a= are methods and not an assignment!
a = [1,2,3]
a[0] = 2 # This is no assignment! It's a method call!
Regards,
Michael
···
On Wed, May 21, 2003 at 05:24:13PM +0900, Frederic Chalons - Design Support IA Student wrote:
On Wed, 21 May 2003, Frederic Chalons - Design Support IA Student wrote:
The = operator seems to retrieve an reference on a Array rather than
copying what it contains
You can find coverage and discussion of Ruby variables at http://www.rubycentral.com/book/tut_classes.html. In short, a
variable holds a reference to an object, so when you assign from one
variable to another, you’re copying that reference.