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

前端 未结 10 872
清歌不尽
清歌不尽 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:36

    I find grep useful here:

    def get_keys(hash)
      ( hash.keys + hash.values.grep(Hash){|sub_hash| get_keys(sub_hash) } ).flatten
    end
    
    p get_keys my_nested_hash #=> ["a", "b", "c"]
    

    I like the solution as it is short, yet it reads very nicely.

提交回复
热议问题