# Hash of Hash to Arr

Hi!

How an I convert a Hash of Hashes to a array (table) (and vice versa)?
h[k1][k2][k3]... = value <=> a[i] = [k1,k2,k3,value]
#CORRECTION: (variable count of keys):
h[k1][k2][k3]... = value <=> a[i] = [k1,k2,k3,.., value] # (
or if you prefer: [value, [k1,...,kn]] )
#k1,k2,k3 = vars vor (many) keys;
# h.recursive_keys.flatten.length == a.length

- hoping s.o. understands, what I'm meaning

thank you
Opti

## just one answer, in the case I don't get any!

This seemed to work for me.

``````def convert_to_arrays(hash)
convert_to_array(hash).flatten(depth_of_hash(hash))
end

def depth_of_hash(hash)
depth = -1
object = hash
begin
object = object.values.first
depth +=1
end while object.is_a?(Hash)
depth
end

def convert_to_array(hash, keys = [])
hash.map do |key, value|
if value.is_a?(Hash)
convert_to_array(value, keys + [key])
else
keys + [key, value]
end
end
end

h1 = {a: {b: {c: 1, d: 2}, e: {f: 3, g: 4}}, h: {i: {j: 5}}}
h2 = {b: {c: 1, d: 2}, e: {f: 3, g: 4}, i: {j: 5}}

p h1
p convert_to_arrays(h1)

p h2
p convert_to_arrays(h2)
``````

Cheers,

Â·Â·Â·

On Mon, Aug 9, 2021 at 8:12 AM Die Optimisten <inform@die-optimisten.net> wrote:

Hi!

How an I convert a Hash of Hashes to a array (table) (and vice versa)?
Â Â Â h[k1][k2][k3]... = value <=> a[i] = [k1,k2,k3,value]
#CORRECTION: (variable count of keys):
Â Â Â h[k1][k2][k3]... = value <=> a[i] = [k1,k2,k3,.., value] # (
or if you prefer: [value, [k1,...,kn]] )
Â Â Â Â #k1,k2,k3 = vars vor (many) keys;
Â Â Â Â # h.recursive_keys.flatten.length == a.length

Â Â Â - hoping s.o. understands, what I'm meaning

thank you
Opti

## just one answer, in the case I don't get any!

Unsubscribe: <mailto:ruby-talk-request@ruby-lang.org?subject=unsubscribe>
<ruby-talk list: member options login page>

--
Andy Maleh