Ruby get object keys as array

Ruby

Ruby Problem Overview


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"]

Ruby Solutions


Solution 1 - Ruby

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

it's that simple

Solution 2 - Ruby

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..

Solution 3 - Ruby

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.

Solution 4 - Ruby

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJD IsaacksView Question on Stackoverflow
Solution 1 - RubyweezorView Answer on Stackoverflow
Solution 2 - RubyTigraineView Answer on Stackoverflow
Solution 3 - RubyJayView Answer on Stackoverflow
Solution 4 - Rubyridecar2View Answer on Stackoverflow