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

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

    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"]
    

提交回复
热议问题