2011-10-18 37 views
1

我不得不重新安排我的目的地的哈希值,所以我想打一個數組中像這樣的數組紅寶石:Mutidimensional陣列上軌

@orderedDestinations = Array.new 
@destinations.each do |destination| 
    if (destination.position != nil) 
    @orderedDestinations[destination.position][destination.id] = destination 
    end 
end 

我得到這個錯誤:

You have a nil object when you didn't expect it! 
You might have expected an instance of Array. 
The error occurred while evaluating nil.[]= 

我做錯了什麼?

+0

偏題,但你應該真的使用'#nil?'謂詞,而不是將對象與'nil'進行比較;) – d11wtq

+1

或者甚至不打擾任何零比較 - 'if destination.position' –

回答

1

在Ruby中,大部分事情都是nil,除非顯式初始化爲某些東西。例如,新數組的所有元素,如果它們不存在或者以前沒有分配過,則默認爲這個元素。像這樣:

test = [ 1, 2 ] 
# => [1,2] 
test[1] 
# => 2 
test[2] 
# => nil 

你可能想要做的是根據需要初始化數組的第二級。您可以採用這樣的模式:

@orderedDestinations = [ ] # Empty array 
@destinations.each do |destination| 
    if (destination.position) 
    # If this element of the array has not been initialized, 
    # populate it with a new empty array. 
    destination_set = @orderedDestinations[destination.position] ||= [ ] 

    # Put something in this second-level array spot 
    destination_set[destination.id] = destination 
    end 
end 

陣列[ ]或哈希{ }你的第二個層次項的選擇取決於你在裏面存儲的數據類型。哈希表很容易處理任意標識符,其中一個數組最適合序列號通常從零開始或接近零開始。如果初始化數組的元素X,則該數組將自動變爲X + 1的大小。

+0

謝謝你的回答。 – Sebastien

2
@orderedDestinations[destination.position] is nil so: 

    @orderedDestinations[destination.position][destination.id] really is: 

    -> nil[destination.id] 
+0

是真的,但是這實在是一個評論,而不是一個答案。 – coreyward

+0

不是,那就是答案。他問他做錯了什麼,我告訴他。簡明扼要,不需要拉伸。 Downvote真的不需要。 – daniel

+0

通常,當有人問他們做錯了什麼時,告訴他們如何正確地做到這一點是恰當的。我同意downvote是不必要的,但它不是我。 :) – coreyward

0

是的, 謝謝。解決的辦法是添加這一行:

@orderedDestinations[destination.position] ||= {} 

所以完整的代碼是:

@orderedDestinations = Array.new 
@destinations.each do |destination| 
    if (destination.position != nil) 
    @orderedDestinations[destination.position] ||= {} 
    @orderedDestinations[destination.position][destination.id] = destination 
    end 
end 

謝謝。

+0

然後你正在創建一個散列。數組和哈希不一樣。 – coreyward

+0

我認爲這是一個合理的做法,考慮到在這裏使用任意'id'值作爲密鑰。 – tadman

+0

@tadman我指出他正在創建一個散列,而不是一個數組,因爲他不清楚他是否知道存在差異。 – coreyward