Ruby gets object keys as an array
I am new to Ruby if I have such an object
{"apple" => "fruit", "carrot" => "vegetable"} How can I return an array of keys only?
["apple", "carrot"] hash = {"apple" => "fruit", "carrot" => "vegetable"} array = hash.keys #=> ["apple", "carrot"] it's 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 this if you wanted to manipulate the array while retrieving it.
Like taro, keys returns an array of keys for your hash:
http://ruby-doc.org/core-1.9.3/Hash.html#method-i-keys
You will find all the different methods available for each class.
If you do not know what you are dealing with:
puts my_unknown_variable.class.to_s This will display the class name.
Use the keys method: {"apple" => "fruit", "carrot" => "vegetable"}.keys == ["apple", "carrot"]