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

前端 未结 10 891
清歌不尽
清歌不尽 2021-01-31 19:02

let\'s have this hash:

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

how can i get all key

10条回答
  •  独厮守ぢ
    2021-01-31 19:31

    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
    

提交回复
热议问题