[英]How do I iterate through a hash where I can view the next key also?
我有一個日期和金錢的哈希,我需要在一組日期之間放入新的貨幣存款。
所以,可以說我的哈希是
{"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
我知道這是無效的,但我需要幫助。 謝謝!
使用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
方面可能與您建議的內容類似。 您可以像
以前=零; a.each_key {| K | p'key is',k,'上一個是',上一個; 前一個= k}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.