2012-11-22 160 views
-1

我正在嘗試做一個小實驗,讓我在此刻陷入困境。將值添加到哈希紅寶石中的哈希值

我創建了新的Hash

tt = Hash.new() 

然後,添加兩個散列裏面的鑰匙:

tt.merge!(:in => Hash.new) 
tt.merge!(:out => Hash.new) 

所以我有一個哈希看起來像這樣:

{ 
    :in => {}, 
    :out => {} 
} 

現在我有另一個叫做res的哈希散列,我遍歷並在每個散列上執行IF語句:

res.each do |x| 
    if x[:id] == nil 
     tt[:out].merge!(x) 
    else 
     tt[:in].merge!(x) 
end 
end 

但是,這隻會將前一個散列的最後一個值附加到新散列的內部和外部。

我所要做的是使用IF語句提出了新的哈希

所以它結束了看起來像IN或OUT的項下:

{ 
    :in => {{:1 => 1 ,:2 => 1 ,:3 => 1 ,:4 => 1 ,:5 => 1 },{:1 => 1 ,:2 => 1 ,:3 => 1 ,:4 => 1 ,:5 => 1 }}, 
    :out => {{:1 => 1 ,:2 => 1 ,:3 => 1 ,:4 => 1 ,:5 => 1 }, {:1 => 1 ,:2 => 1 ,:3 => 1 ,:4 => 1 ,:5 => 1 }} 
} 

而且 - 我應該使用哈希這個或數組?我想將它最終導出爲JSON。

例如,這可以工作。但不知道這是否是正確的:

tt = Hash.new(:in => Hash.new, :out => Hash.new) 
tt.merge!(:in => Array.new) 
tt.merge!(:out => Array.new) 
ap tt.class 
res.each do |x| 
    if x[:id] == nil 
     tt[:out] << x 
    else 
     tt[:in] << x 
end 
end 

Thnaks

+0

你說'res'是一個散列,但你的'res.each'只包含一個參數。通常你需要兩個:鍵和值。你可以發佈一個'res'的例子嗎? – knut

回答

0

這是不可能的。你正在談論{1,2,3,4,5}作爲散列,但它是不是散列,它是一個數組。如果您沒有與值關聯的特定鍵,則不會有類似散列的數據。你使用數組的第二個版本是正確的(除了使用merge ...請參見下文)。

此外,如果你想添加一些散列,你應該使用[]運算符,而不是重複使用merge

例如,這是錯誤的:

tt = Hash.new() 
tt.merge!(:in => Hash.new) 
tt.merge!(:out => Hash.new) 

你想要什麼或者是這樣的:

tt = Hash.new() 
tt[:in] = Hash.new 
tt[:out] = Hash.new 

或更好的做法是:

tt = { in: {}, out: {} } 

完整和正確版本的這可能看起來像這樣:

tt = Hash.new(in: [], out: []) 

res.each do |x| 
    if x[:id].nil? 
    tt[:out] << x 
    else 
    tt[:in] << x 
end 
+0

謝謝!我已經更新了我的哈希示例對不起,它粘貼錯了。他們不只是1,2,3,4 –