我将编写一个方法,接收嵌套的哈希作为输入,并返回带有“深度”键的哈希。例如,以下输入:
tree = {
a: 1,
b: 2,
c: { d: { e: 3 } }
}
将产生以下返回值:
{
a: 1,
b: 2,
c: {
d: {
e: 3,
depth: 2
},
depth: 1
},
depth: 0
}
如果输入不是哈希表,则该函数应返回nil。
这是我想出的方案:
def depth(hash)
num = 0
hash.each do |key, value|
if value.class == Hash
num += 1
v[:depth] = num
value.each do |k, v|
if v.class == Hash
num += 1
v[:depth] = num
v.each do |ky, val|
if val.class == Hash
num += 1
v[:depth] = num
val.each do |ke, vl|
if vl.class == Hash
num += 1
v[:depth] = num
end
end
end
end
end
end
end
num = 0
end
end
但它仅限于哈希深度为4,我不能一直让这个方法变得更大。