繁体   English   中英

如何遍历哈希值,在哈希值中还可以查看下一个键?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM