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

前端 未结 10 868
清歌不尽
清歌不尽 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
    def get_all_keys(hash)
      hash.map do |k, v|
        Hash === v ? [k, get_all_keys(v)] : [k]
      end.flatten
    end
    
    0 讨论(0)
  • 2021-01-31 19:40

    hash.keys is the simplest one I have seen to return an array of the key values in a hash.

    0 讨论(0)
  • 2021-01-31 19:41
    class Hash
    
      def get_all_keys
        [].tap do |result|
          result << keys
          values.select { |v| v.respond_to?(:get_all_keys) }.each do |value| 
            result << value.get_all_keys
          end
        end.flatten
      end
    
    end
    
    hash = {"a" => 1, "b" => {"c" => 3}}
    puts hash.get_all_keys.inspect # => ["a", "b", "c"]
    
    0 讨论(0)
  • 2021-01-31 19:41

    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"]
    
    0 讨论(0)
提交回复
热议问题