Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

let's have this hash:

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

how can i get all keys since hash.keys returns just ["a", "b"]

like image 551
user2211703 Avatar asked Nov 27 '13 06:11

user2211703


People also ask

How do you get the key of a hash in Ruby?

hash.fetch(key) { | key | block } Returns a value from hash for the given key. If the key can't be found, and there are no other arguments, it raises an IndexError exception; if default is given, it is returned; if the optional block is specified, its result is returned.

Can a hash have multiple values Ruby?

Each key can only have one value. But the same value can occur more than once inside a Hash, while each key can occur only once.

How do you combine hashes in Ruby?

We can merge two hashes using the merge() method. When using the merge() method: Each new entry is added to the end. Each duplicate-key entry's value overwrites the previous value.


2 Answers

This will give you an array of all the keys for any level of nesting.

def get_em(h)   h.each_with_object([]) do |(k,v),keys|           keys << k     keys.concat(get_em(v)) if v.is_a? Hash   end end  hash = {"a" => 1, "b" => {"c" => {"d" => 3}}} get_em(hash) #  => ["a", "b", "c", "d"] 
like image 102
Cary Swoveland Avatar answered Sep 18 '22 17:09

Cary Swoveland


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.

like image 27
hirolau Avatar answered Sep 18 '22 17:09

hirolau