2010-08-25 27 views
2

我有日期錢的哈希值,我需要把新錢存款其間的一組日期。如何迭代散列,我也可以查看下一個鍵?

因此,可以說,我的哈希

{"000000001" => "0.00", "000000002" ="12.34", "000000010" => "5.95"} 

,我要插入000000008, 54.34然後我得到的散列應該

{"000000001" => "0.00", "000000002" ="66.68", "000000010" => "5.95"} 

*(這些例子時間戳)

所以...我想這樣...

my_hash.each_with_index do |key_value, index| 
    if index == my_hash.length then return my_hash end 
    if time >= my_hash[dat[0]][0].to_i and time <= my_hash[dat[0]].next[0].to_i 
     my_hash[index][1] += value 
    end 
    end 
end 

我知道這是無效的,但我需要幫助。謝謝!

+0

參見http://stackoverflow.com/questions/3478486/loops-within-ruby – 2010-08-25 14:35:29

回答

5

使用each_cons

{ 
    "000000001" => "0.00", "000000002" => "66.68", "000000010" => "5.95" 
}.each_cons(2) do |(prev_key, prev_value), (next_key, next_value)| 
    p "#{prev_key} preceedes #{next_key}" 
end 
0

方面可能有像你提出了什麼。 你可以得到以前一樣關鍵

以往=零; a.each_key {| K | p'鍵是',k',前一個是',前一個;以往= K}