在Ruby中返回嵌套哈希的最大深度的好方法吗

在Ruby中返回嵌套哈希的最大深度的好方法吗,ruby,hash,Ruby,Hash,哈希对象如下所示,它既有数组值也有哈希值,但嵌套总是发生在“children”数组的值上: 这将找到任何嵌套哈希的深度,也将遍历数组并为它们指定一个零深度 class Hash def max_depth 1 + values.map do |val| if val.respond_to?(:max_depth) val.max_depth elsif val.respond_to?(:max) val.max { |elt

哈希对象如下所示,它既有数组值也有哈希值,但嵌套总是发生在“children”数组的值上:


这将找到任何嵌套哈希的深度,也将遍历数组并为它们指定一个零深度

class Hash
  def max_depth
    1 + values.map do |val| 
      if val.respond_to?(:max_depth) 
        val.max_depth
      elsif val.respond_to?(:max)
        val.max { |elt| elt.max_depth }
      else
        0
      end
    end.max
  end
end

这应该适用于您的情况:

def array_traverse(array, depth)
  array.each do |i|
    if i.class == Array
      depth = array_traverse(i, depth)
    elsif i.class == Hash
      depth = hash_traverse(i, depth)
    end
  end
  return depth
end

def hash_traverse(hash, depth)
  hash.keys().each do |i|
    depth += 1 if i == 'children' and hash[i].length > 1
    if hash[i].class == Array
      depth = array_traverse(hash[i], depth)
    elsif hash[i].class == Hash
      depth = hash_traverse(hash[i], depth)
    end
  end
  return depth
end

puts hash_traverse(a, 1)

如果您特别想找到“children”键的深度,可以使用以下方法:

class Hash
  def max_depth
    max_depth = 1
    depth_func = ->(hsh, cur_depth) do
      max_depth = cur_depth if cur_depth > max_depth
      hsh["children"].to_a.each{|h| depth_func.call(h, cur_depth+1)}
      max_depth
    end
    depth_func.call(self, 0)
  end
end
现在,您可以尝试以下代码:

h = {  "id" => "1", "children" => [{"id"=>"11", "children"=>[{"id"=>"111"}]}, 
       {"id"=>"12", "children"=>[{"id"=>"121", "children"=>[{"id"=>"1211"}]}, 
       {"id"=>"122"}]}]}

h.max_depth # 3
以下(非递归)实例方法
Hash#depth
返回所需的深度度量。我添加了一个
put
语句来显示中间计算

class Hash
  def depth
    arr = values
    d = 0
    loop do
      arr = arr.flatten.select { |e| e.is_a? Hash }
      break d if arr.empty?
      d += 1
      arr = arr.map(&:values)
      puts "d = #{d}, arr = #{arr}"
    end
  end
end

a.depth
d = 1, arr = [["11", [{"id"=>"111"}]], ["12", [{"id"=>"121", "children"=>
                [{"id"=>"1211"}]}, {"id"=>"122"}]]]
d = 2, arr = [["111"], ["121", [{"id"=>"1211"}]], ["122"]]
d = 3, arr = [["1211"]]
  #=> 3

如果将嵌套数组作为值,该怎么办?在数组中封装哈希时,它有多深?到目前为止你都试了些什么?很公平。完成。谢谢。您可以简单地用
值替换
值。map
在第一个版本上,我修改了示例,将
.map{…}.max
替换为
.max{…}
,因为。请查看您的代码:`a.max{u depth}=>ArgumentError:0的哈希比较失败
,其中
a`iis是OP的哈希。这不会返回我的深度either@shigazaru它适用于我的样品。你能提供它不起作用的哈希吗。
class Hash
  def depth
    arr = values
    d = 0
    loop do
      arr = arr.flatten.select { |e| e.is_a? Hash }
      break d if arr.empty?
      d += 1
      arr = arr.map(&:values)
      puts "d = #{d}, arr = #{arr}"
    end
  end
end

a.depth
d = 1, arr = [["11", [{"id"=>"111"}]], ["12", [{"id"=>"121", "children"=>
                [{"id"=>"1211"}]}, {"id"=>"122"}]]]
d = 2, arr = [["111"], ["121", [{"id"=>"1211"}]], ["122"]]
d = 3, arr = [["1211"]]
  #=> 3