2014-05-19 183 views
0

我有這個散列:我怎樣才能把一個長長的紅寶石哈希分成多行?

arr={ [0,1]=>[0,0,1,1], [0,2]=>[0,1,0,1], [0,3]=>[0,1,1,0], [1,2]=>[1,0,0,1], [1,3] =>[1,0,1,0], [2,3] => [1,1,0,0] } 

,我希望把它分解爲兩行,因爲它是很長,在121個字符。我不是對線路長度的標籤,但我的指導線爲80,這個時間比我更喜歡

所以我試圖

arr={ [0,1] => [0,0,1,1], [0,2] => [0,1,0,1], [0,3] => [0,1,1,0] } 
    arr.merge({[1,2] => [1,0,0,1], [1,3] => [1,0,1,0], [2,3] => [1,1,0,0]}) 

,但我的測試失敗,並有錯誤,如

undefined method `[]' for nil:NilClass 

我該如何更好地解決這個問題?一個選項是續行\,但看起來並不特別整齊。

arr={ [0,1]=>[0,0,1,1], [0,2]=>[0,1,0,1], [0,3]=>[0,1,1,0], \ 
[1,2]=>[1,0,0,1], [1,3] =>[1,0,1,0], [2,3] => [1,1,0,0] } 

但我想我能做到

arr={ [0,1]=>[0,0,1,1], [0,2]=>[0,1,0,1], [0,3]=>[0,1,1,0], \ 
     [1,2]=>[1,0,0,1], [1,3] =>[1,0,1,0], [2,3] => [1,1,0,0] } 

,但看起來像W¯¯空白維護氣味縮進。

有沒有更好的選擇?

+1

...您不需要在這裏繼續行,只需用逗號結束行。 –

回答

4
arr = { 
    [0,1] => [0,0,1,1], [0,2] => [0,1,0,1], [0,3] => [0,1,1,0], 
    [1,2] => [1,0,0,1], [1,3] => [1,0,1,0], [2,3] => [1,1,0,0] 
} 
1

我寧願把它寫這樣的:

arr = { 
    [0,1] => [0,0,1,1], 
    [0,2] => [0,1,0,1], 
    [0,3] => [0,1,1,0], 
    [1,2] => [1,0,0,1], 
    [1,3] => [1,0,1,0], 
    [2,3] => [1,1,0,0] 
} 

這是更可讀。另外我假設你知道使用數組作爲鍵的後果?

2

您嘗試merge失敗,因爲#merge不會更改您調用的對象,但它會返回一個新的合併對象。它的工作,你需要使用#merge!

arr={ [0,1] => [0,0,1,1], [0,2] => [0,1,0,1], [0,3] => [0,1,1,0] } 
arr.merge!([1,2] => [1,0,0,1], [1,3] => [1,0,1,0], [2,3] => [1,1,0,0]) 

這是很矯枉過正,但是,作爲多襯哈希是很容易的,因爲在其他的答案說。