Ruby get object keys as array
Solution 1:
hash = {"apple" => "fruit", "carrot" => "vegetable"}
array = hash.keys #=> ["apple", "carrot"]
it's that simple
Solution 2:
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:
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.