创建一个方法
def flatten_hash_keys(hash, prefix = nil)
flat_keys = []
hash.each do |key, value|
current_key = prefix ? "#{prefix}.#{key}" : key.to_s
if value.is_a?(Hash) && !value.empty?
flat_keys.concat(flatten_hash_keys(value, current_key))
else
flat_keys << current_key
end
end
flat_keys
end
这段代码定义了一个采用散列和可选前缀的Flatten_hash_key方法.它递归地遍历散列,将键附加到Flat_Keysarray.如果值是非空哈希,则使用新前缀递归调用该方法.否则,当前密钥将添加到数组中
input1 = {a: {b: {c: {} }, d:[] }, e: "e", f: nil, g: -2}
input2 = {a: {b: {c: {h: {j: ''}, m: {n: ''}}}, d: {k: {l: '' } }},e: "e",f: nil,g: -2}
output1 = flatten_hash_keys(input1) #["a.b.c", "a.d", "e", "f", "g"]
output2 = flatten_hash_keys(input2) #["a.b.c.h.j", "a.b.c.m.n", "a.d.k.l", "e", "f", "g"]