Neil Hoff
Neil Hoff

Reputation: 2085

How can I get the keys in a multidimensional hash in Ruby?

So with a normal hash you can use this to get the keys:

hash.keys

How can I get the keys of the 2nd dimension of a multidimensional hash that looks like this:

{"<id>"=>{"first_name"=>"test", "last_name"=>"test_l", "username"=>"test_user", 
"title"=>"Sales Manager", "office"=>"test", "email"=>"[email protected]"}}

<id> is unique for each item.

So the keys I want from above are: first_name, last_name, username, title, office and email

Upvotes: 5

Views: 4746

Answers (4)

rickyrickyrice
rickyrickyrice

Reputation: 577

I'm assuming you mean there will be several unique "id" keys in the base hash that point to nested hashes that each contain the "first_name", "last_name", etc. keys. If that's the case:

hash.values.map(&:keys)

will return an array of arrays containing the keys of each nested hash.

On the other hand, if you only have one key-value pair (as in your example), you could do

hash.values.first.keys

which would return a flat array of keys corresponding to those in the lone nested hash.

Upvotes: 3

steenslag
steenslag

Reputation: 80105

Assuming you have a hash which has one unknown key with one value : a hash.

h = {"<id>"=>{"first_name"=>"test", "last_name"=>"test_l", "username"=>"test_user", 
"title"=>"Sales Manager", "office"=>"test", "email"=>"[email protected]"}}

p h[h.keys.first].keys
#=> ["first_name", "last_name", "username", "title", "office", "email"]

(But every time I see a construct like this I wonder why it isn't a Struct).

Upvotes: 2

Don Cruickshank
Don Cruickshank

Reputation: 5948

The following would get you all the keys used in the second level hashes. I've used uniq so that you don't get duplicates.

hash.collect { |k, v| v.keys }.flatten.uniq

Upvotes: 3

BlackHatSamurai
BlackHatSamurai

Reputation: 23503

You would do something like:

hash["<id>"].keys

Upvotes: 4

Related Questions