Recursively push the key value pair to hash with indiffernt access
I am new to ruby on rails and开发者_如何学Python I am trying do something like, I have hash
hash1 = {"a"=>"1","b"=>{"c"=>"3","d"=>{"e"=>"5"}},"f"=>"6","g"=>{"h"=>"7","i"=>"8"}}
Then i used a recursive method to read the key-value pair, as shown below :
def traverse_hash_recursively(words)
words.each_pair do |key,value|
if value.is_a?(String)
puts "#{key}=>#{value}"
else
traverse_hash_recursively(value)
end
end
end
called the above method like this :
traverse_hash_recursively(hash1)
and the output is like :
a=>1
c=>3
e=>5
f=>6
h=>7
i=>8
But this is not the output i was looking for, i want the output as
hash[a]=1
hash[b][c]=3
hash[b][d][e]=5
hash[f]=6
hash[g][h]=7
hash[g][i]=8
I know what i have written in the code will give me the output i got but how will i get the desired output? Can anybody help?
We need a stack that will keep track of the keys
def traverse_hash_recursively(keys, words)
words.each_pair do |key,value|
keys << key
if value.is_a?(String)
puts "#{keys.join(',')}=>#{value}"
keys.pop
else
traverse_hash_recursively(keys, value)
keys.pop
end
end
end
And you should call the function with an empty stack.
traverse_hash_recursively([], hash1)
Output =>
a=>1
b,c=>3
b,d,e=>5
f=>6
g,h=>7
g,i=>8
Now, the rest is just formatting.
精彩评论