Ruby: Get all keys in a hash (including sub keys)

2019-03-09 21:00发布

let's have this hash:

hash = {"a" => 1, "b" => {"c" => 3}}
hash.get_all_keys 
=> ["a", "b", "c"]

how can i get all keys since hash.keys returns just ["a", "b"]

标签: ruby hash
10条回答
Ridiculous、
2楼-- · 2019-03-09 21:36

Please take a look of following code:

hash = {"a" => 1, "b" => {"c" => 3}}
keys = hash.keys + hash.select{|_,value|value.is_a?(Hash)}
       .map{|_,value| value.keys}.flatten
p keys

result:

["a", "b", "c"]

New solution, considering @Bala's comments.

class Hash
  def recursive_keys
    if any?{|_,value| value.is_a?(Hash)}
       keys + select{|_,value|value.is_a?(Hash)}
                    .map{|_,value| value.recursive_keys}.flatten
    else
       keys
    end
  end
end

hash =  {"a" => 1, "b" => {"c" => {"d" => 3}}, "e" => {"f" => 3}}
p hash.recursive_keys

result:

["a", "b", "e", "c", "d", "f"]
查看更多
家丑人穷心不美
3楼-- · 2019-03-09 21:41
def get_all_keys(hash)
  hash.map do |k, v|
    Hash === v ? [k, get_all_keys(v)] : [k]
  end.flatten
end
查看更多
Deceive 欺骗
4楼-- · 2019-03-09 21:42

Here is another approach :

def get_all_keys(h)
  h.each_with_object([]){|(k,v),a| v.is_a?(Hash) ? a.push(k,*get_all_keys(v)) : a << k }
end

hash = {"a" => 1, "b" => {"c" => {"d" => 3}}}
p get_all_keys(hash)
# >> ["a", "b", "c", "d"]
查看更多
手持菜刀,她持情操
5楼-- · 2019-03-09 21:42

I'm sure there is a more elegant solution, but this option works:

blah = {"a" => 1, "b" => {"c" => 3}}
results = []
blah.each do |k,v|
  if v.is_a? Hash
    results << k
    v.each_key {|key| results << key}
  else
    results << k
  end
end
puts results
查看更多
登录 后发表回答