[英]How do I iterate through a hash where I can view the next key also?
I have a hash of dates to money, and I need to put new money deposits inbetween a set of dates. 我有一个日期和金钱的哈希,我需要在一组日期之间放入新的货币存款。
so, lets say my hash is 所以,可以说我的哈希是
{"000000001" => "0.00", "000000002" ="12.34", "000000010" => "5.95"}
and I want to insert 000000008, 54.34
then my resulting hash should be 我想插入
000000008, 54.34
那么我得到的哈希应该是
{"000000001" => "0.00", "000000002" ="66.68", "000000010" => "5.95"}
*(These are example time stamps) *(这些是示例时间戳)
so... I was thinking something like... 所以...我在想...
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
which I know is invalid, but I need help. 我知道这是无效的,但我需要帮助。 Thanks!
谢谢!
Use each_cons
: 使用
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
facets probably has something like what you proposed. 方面可能与您建议的内容类似。 You can get the previous key like
您可以像
previous = nil; 以前=零; a.each_key{|k|
a.each_key {| K | p 'key is', k, 'previous is', previous;
p'key is',k,'上一个是',上一个; previous = k}
前一个= k}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.