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
{"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开发者_StackOverflow社区
end
end
end
which I know is invalid, but I need help. Thanks!
Use 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| p 'key is', k, 'previous is', previous; previous = k}
精彩评论