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"]
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.
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.
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.
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"]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With