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

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

hash.keys

How can I get the keys of the second 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"=>"test@test.com"}}

<id> unique to each item.

So the keys that I want on top are as follows: first_name, last_name, username, title, office and email

+5
source share
4 answers

Assuming you have a hash that 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"=>"test@test.com"}}

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

(But every time I see such a design, I wonder why it is not Struct).

+2
source

You would do something like:

hash["<id>"].keys
+4
source

, . uniq, .

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

I assume that you mean that the base hash will have several unique "id" keys that point to nested hashes in which each contains the keys "first_name", "last_name", etc. If this is the case:

hash.values.map(&:keys)

returns an array of arrays containing the keys of each nested hash.

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

hash.values.first.keys

which will return an even array of keys corresponding to those in a single nested hash.

+2
source

All Articles