I have an array of hashes:
[{"sex"=>"male"}, {"sex"=>"male"}, {"sex"=>"female"}]
How can I convert it to array of values:
["male", "male", "female"]
A generic approach to this that would take into account other possible keys:
list = [{"sex"=>"male"}, {"sex"=>"male"}, {"sex"=>"female"}]
# Collect the 'sex' key of each hash item in the list.
sexes = list.collect { |e| e['sex'] }
arr = [{"sex"=>"male"}, {"sex"=>"male"}, {"sex"=>"female"}]
arr.map(&:values).flatten
EDIT: As directed by @tadman. Thanks!
flatten will do the job.flatten! call only affects the result of the map operation, and does not modify arr.You can "map" the elements inside array, take the values of hashes, them "flatten" the resultant array.
[{"sex"=>"male"}, {"sex"=>"male"}, {"sex"=>"female"}].map{|h| h.values }
=> [["male"], ["male"], ["female"]]
[["male"], ["male"], ["female"]].flatten
=> ["male", "male", "female"]
In a single line, you can:
[{"sex"=>"male"}, {"sex"=>"male"}, {"sex"=>"female"}].map{|h| h.values }.flatten
or:
[{"sex"=>"male"}, {"sex"=>"male"}, {"sex"=>"female"}].map(&:values).flatten
Docs:
arr = Array.new
my_hash.each do |el|
#collect them here...
arr.push(el["sex"]);
end
Hope it helps