如何检索Ruby中哈希中的所有键,以及嵌套的键。重复的内容应该被忽略。
{ a: 3, b: { b: 2, b: { c: 5 } } }.soberize
=> [:a, :b, :c]最快的实现是什么?
发布于 2013-12-10 23:14:36
简单递归解决方案:
def recursive_keys(data)
data.keys + data.values.map{|value| recursive_keys(value) if value.is_a?(Hash) }
end
def all_keys(data)
recursive_keys(data).flatten.compact.uniq
end 用法:
all_keys({ a: 3, b: { b: 2, b: { c: 5 } } })
=> [:a, :b, :c]发布于 2013-12-10 23:19:01
递归方法呢?
def nested_keys(hash, array)
if hash.is_a?(Hash)
array |= hash.keys
hash.keys.map do |key|
array = nested_keys(hash[key], array)
end
end
array
endhttps://stackoverflow.com/questions/20506847
复制相似问题