Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

hash

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

like image 767
Neil Hoff Avatar asked Feb 25 '13 22:02

Neil Hoff


People also ask

How do I get the key-value in Ruby?

You can find a key that leads to a certain value with Hash#key . If you are using a Ruby earlier than 1.9, you can use Hash#index . Once you have a key (the keys) that lead to the value, you can compare them and act on them with if/unless/case expressions, custom methods that take blocks, et cetera.

How do you check if a hash has a key Ruby?

Overview. We can check if a particular hash contains a particular key by using the method has_key?(key) . It returns true or false depending on whether the key exists in the hash or not.

How do you remove a key from a hash in Ruby?

Ruby | Hash delete() function delete() is an Hash class method which deletes the key-value pair and returns the value from hash whose key is equal to key. Return: value from hash whose key is equal to deleted key.


1 Answers

You would do something like:

hash["<id>"].keys
like image 110
BlackHatSamurai Avatar answered Oct 16 '22 22:10

BlackHatSamurai