Retrieve all keys for complex hash without knowing keyname

Hi all,

I have been trying to find a solution for this for quite sometime now.
I have a complex hash structure something like this eg
{“user”=>{“name”=>“test”, “address”=>{“line1”=>“bethesda”,

I need to retrieve all the keys for this hash or any kind of hash simple
or complex(generic solution).

I do not know any keys names but want the entire list in an array.

Final output =
[ “user”][“name”],
[ “user”][“address”][“line1”],
[ “user”][“address”][“town”]

array = hash.keys returns for a simple hash structure but would not work
for the above kind.
Would this be possible? Thanks for looking into it

data={“user”=>{“name”=>“test”, “address”=>{“line1”=>“bethesda”,

def fk(h,l=[],&b)
return yield(l) unless h.kind_of?(Hash)
h.each {|k,v| fk(v,l+[k],&b) }

fk(data) {|a| p a}

ruby t.rb
[“user”, “name”]
[“user”, “address”, “line1”]
[“user”, “address”, “town”]

or :

def fk3(h,l=[],lout=[])
h.kind_of?(Hash) ? h.each {|k,v| fk3(v,l+[k],lout) } : lout << l

p fk3(data)

ruby t.rb
[[“user”, “name”], [“user”, “address”, “line1”], [“user”, “address”,

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs