"fruit", "carrot" => "vegetable"} How can I return an...">

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"] 
+71
ruby
Dec 28 '11 at 3:26 a.m.
source share
4 answers
 hash = {"apple" => "fruit", "carrot" => "vegetable"} array = hash.keys #=> ["apple", "carrot"] 

it's simple

+159
Dec 28 '11 at 15:30
source share

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.

+10
Dec 28 '11 at 17:45
source share

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.

+4
Dec 28 '11 at 15:36
source share

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

+1
Dec 28 '11 at 15:31
source share



All Articles