Reputation: 20415
I have an array of hashes:
[{"sex"=>"male"}, {"sex"=>"male"}, {"sex"=>"female"}]
How can I convert it to array of values:
["male", "male", "female"]
Upvotes: 2
Views: 121
Reputation: 13014
arr = [{"sex"=>"male"}, {"sex"=>"male"}, {"sex"=>"female"}]
arr.map(&:values).flatten
EDIT: As directed by @tadman. Thanks!
Upvotes: 2
Reputation: 712
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:
Upvotes: 1
Reputation: 263
arr = Array.new
my_hash.each do |el|
#collect them here...
arr.push(el["sex"]);
end
Hope it helps
Upvotes: -2
Reputation: 118261
[{"sex"=>"male"}, {"sex"=>"male"}, {"sex"=>"female"}].flat_map(&:values)
Upvotes: 4
Reputation: 211560
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'] }
Upvotes: 2
Reputation: 5617
In this case,
[{"sex"=>"male"}, {"sex"=>"male"}, {"sex"=>"female"}].map(&:values).flatten
should work.
It takes an array from each hash, then flatten the nested array.
Upvotes: 4