2d array variable overwrite doesn't work in ruby?
I can't seem to be able to override a variable in my ruby code.
i have two 2d arrays called table
and updated_table
, updated_table
inherits the values of table
and that works, but then later in the code, changes are made to the values of the updated_tabl开发者_运维百科e
and when i try to set the updated_table
back to the same values(state) of table
this doesn't work.
why is that? very simple example of what im trying to do.
class SomeClass
table = [[0,20,5,1000,1000], [20,0,10,8,20], [5,10,0,1000,40], [1000,8,1000,0,6], [1000,20,40,6,0]]
updated_table = table
##
then here i have some code that makes changes to the values in the updated_table
##
2.times do
updated_table = table # this dosent work??
## do some more calculations and so on ##
end
end
You made updated_table
a reference to table
when you called updated_table = table
. They both point to the exact same table. When you modified updated_table
you actually updated table
at the same time.
I believe you want updated_table = table.dup
.
In Ruby, variables do not contain the object itself. They are said to point to or reference the object in memory. So, when you write updated_table = table
, you are not making a copy of the object, you are just creating another reference to that object.
You can create a separate although identical object with the Object#dup
method.
updated_table = table.dup
This is a shallow copy, due to the fact that the array holds references to objects, and these objects are not duplicated themselves. This means that both the original array and the duplicate effectively reference the same elements, so keep this in mind if you need to modify objects stored inside either array.
Will deep copying achieve your intended result?
I think the reason your code wasn't working as expected was each time you made a change to updated table, it was automatically changing the original because of how you'd copied (referenced) it in the first place.
I don't think object.dup
will work as you want, because your array is 2 dimensional. See here - http://ruby.about.com/od/advancedruby/a/deepcopy.htm - for good further reading (with array based examples) on the subject of object.dup, clone and marshalling to find out why.
I've just simply added a snippet to deep copy the table rather than cloning it.
# Deep copy - http://www.ruby-forum.com/topic/121005
# Thanks to Wayne E. Seguin.
class Object
def deep_copy( object )
Marshal.load( Marshal.dump( object ) )
end
end
table = [[0,20,5,1000,1000], [20,0,10,8,20], [5,10,0,1000,40], [1000,8,1000,0,6], [1000,20,40,6,0]]
updated_table = deep_copy(table) # -- DON'T CLONE TABLE, DEEP COPY INSTEAD --
##
# then here i have some code that makes changes to the values in the updated_table
##
2.times do
updated_table = deep_copy(table) # -- USE DEEP_COPY HERE TOO --
## do some more calculations and so on ##
end
精彩评论