Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby get object keys as array

Tags:

ruby

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"] 
like image 304
JD Isaacks Avatar asked Dec 28 '11 15:12

JD Isaacks


Video Answer


2 Answers

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

it's that simple

like image 166
weezor Avatar answered Sep 28 '22 18:09

weezor


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

like image 22
Tigraine Avatar answered Sep 28 '22 17:09

Tigraine