lilixiaocc lilixiaocc - 3 months ago 7
Ruby Question

print out Hash key and value pairs recursively

I am trying to define a function that it can print out any hash values in a tree format. The function will do something like this:

From

{"parent1"=>
{"child1" => { "grandchild1" => 1,
"grandchild2" => 2},
"child2" => { "grandchild3" => 3,
"grandchild4" => 4}}
}


To

parent1:
child1:
grandchild1:1
grandchild2:2
child2:
grandchild3:3
grandchild4:4


And this is my code so far:

def readprop(foo)
level = ''
if foo.is_a?(Hash)
foo.each_key {|key| if foo[key].nil? == false
puts level + key + ":"
level += " "
readprop(foo[key])
end
}
else
puts level + foo
level = level[0,level.length - 2]
end
end


and it will give me a bad format like this:

parent1:
child1:
grandchild1:
1
grandchild2:
2
child2:
grandchild3:
3
grandchild4:
4

Answer

You are almost there. One way to solve it is to make level a part of the recursive function parameters.

Simple recursive version:

def print_hash(h,spaces=4,level=0)
  h.each do |key,val|
    format = "#{' '*spaces*level}#{key}: "
    if val.is_a? Hash
      puts format
      print_hash(val,spaces,level+1)
    else
      puts format + val.to_s
    end
  end
end

print_hash(x)

#parent1: 
#    child1: 
#        grandchild1: 1
#        grandchild2: 2
#    child2: 
#        grandchild3: 3
#        grandchild4: 4