ruby – 递归打印出散列键和值对
发布时间:2020-12-16 23:33:14 所属栏目:百科 来源:网络整理
导读:我试图定义一个函数,它可以打印出树格式的任何哈希值.该函数将执行以下操作: 从 {"parent1"= {"child1" = { "grandchild1" = 1,"grandchild2" = 2},"child2" = { "grandchild3" = 3,"grandchild4" = 4}}} 至 parent1: child1: grandchild1:1 grandchild2:2
我试图定义一个函数,它可以打印出树格式的任何哈希值.该函数将执行以下操作:
从 {"parent1"=> {"child1" => { "grandchild1" => 1,"grandchild2" => 2},"child2" => { "grandchild3" => 3,"grandchild4" => 4}} } 至 parent1: child1: grandchild1:1 grandchild2:2 child2: grandchild3:3 grandchild4:4 到目前为止这是我的代码: 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 它会给我一个像这样的错误格式: parent1: child1: grandchild1: 1 grandchild2: 2 child2: grandchild3: 3 grandchild4: 4 解决方法
你快到了.解决它的一种方法是使级别成为递归函数参数的一部分. x是问题中的哈希值.
简单的递归版本: 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 在这种情况下,您还可以将其转换为YAML(如上面的评论中所述) require 'YAML' puts x.to_yaml #--- #parent1: # child1: # grandchild1: 1 # grandchild2: 2 # child2: # grandchild3: 3 # grandchild4: 4 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |