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

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

    Also deal with nested arrays that include hashes

    def all_keys(items)
      case items
      when Hash then items.keys + items.values.flat_map { |v| all_keys(v) }
      when Array then items.flat_map { |i| all_keys(i) }
      else []
      end
    end
    

提交回复
热议问题