[ruby] Ruby get object keys as array

I am new to Ruby, if I have an object like this

{"apple" => "fruit", "carrot" => "vegetable"}

How can I return an array of just the keys?

["apple", "carrot"]

This question is related to ruby

The answer is


hash = {"apple" => "fruit", "carrot" => "vegetable"}
array = hash.keys   #=> ["apple", "carrot"]

it's that simple


An alternative way if you need something more (besides using the keys method):

hash = {"apple" => "fruit", "carrot" => "vegetable"}
array = hash.collect {|key,value| key }

obviously you would only do that if you want to manipulate the array while retrieving it..


Like taro said, keys returns the array of keys of your Hash:

http://ruby-doc.org/core-1.9.3/Hash.html#method-i-keys

You'll find all the different methods available for each class.

If you don't know what you're dealing with:

 puts my_unknown_variable.class.to_s

This will output the class name.


Use the keys method: {"apple" => "fruit", "carrot" => "vegetable"}.keys == ["apple", "carrot"]