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"]
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..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With