2011-03-05 40 views
1

我似乎無法重寫我的紅寶石代碼中的變量。2d數組變量覆蓋在ruby中不起作用?

我有兩個二維數組稱爲tableupdated_tableupdated_table繼承的table的價值觀和工作,但隨後在後面的代碼,更改了updated_table的值進行,當我嘗試設置updated_table回相同的值(州)table這不起作用。

這是爲什麼? 我試圖做的很簡單的例子。

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 
+0

你爲什麼要這樣做兩次? (你也可以做'2times') – 2011-03-05 03:05:07

+0

這只是一個例子,實際代碼中有邏輯確定每次循環和計算這個表的次數。 – 2011-03-05 03:07:13

回答

1

深拷貝實現您的預​​期結果?

我認爲你的代碼沒有按預期工作的原因是每當你對更新表進行更改時,它都會自動更改原來的原因,因爲你原來如何複製(引用)它。

我不認爲object.dup會按你的意願工作,因爲你的數組是二維的。看到這裏 - http://ruby.about.com/od/advancedruby/a/deepcopy.htm - 爲了進一步閱讀(使用基於數組的示例),瞭解object.dup,clone和marshalling的主題以找出原因。

我只是簡單地添加了一個片段來深度複製表格而不是克隆它。

# 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 
+0

嗨,謝謝你的回答,每次我想覆蓋一個變量內容時,我是否必須使用它? – 2011-03-05 11:40:25

+0

@Mo,No.您可以照常更改個別元素,例如'updated_table [0] [0] = 100'。只有當你想'複製'表格的內容時才進行深層複製。 – bluekeys 2011-03-05 11:52:21

+0

你是對的,.dup沒有工作。謝謝,我試圖調試大約2個小時的問題。 – 2011-03-05 20:29:30

2

你讓updated_table一個參考table當你叫updated_table = table。他們都指向完全相同的表格。當您修改updated_table時,您實際上同時更新了table

我相信你想updated_table = table.dup

2

在Ruby中,變量不包含對象本身。他們被稱爲指向參考在內存中的對象。所以,當你寫updated_table = table時,你並沒有製作該對象的副本,而只是創建了該對象的另一個引用。

您可以使用Object#dup方法創建一個單獨的雖然相同的對象。

updated_table = table.dup 

這是一個淺拷貝,由於該數組保存對對象的引用,這些對象不重複自己的事實。這意味着原始數組和重複數據都有效地引用了相同的元素,因此如果需要修改存儲在數組中的對象,請記住這一點。