AdamNYC
AdamNYC

Reputation: 20415

How can I convert an array of hashes to an array of hash values?

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

Answers (6)

kiddorails
kiddorails

Reputation: 13014

arr = [{"sex"=>"male"}, {"sex"=>"male"}, {"sex"=>"female"}]
arr.map(&:values).flatten

EDIT: As directed by @tadman. Thanks!

Upvotes: 2

Philip Sampaio
Philip Sampaio

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

lrl
lrl

Reputation: 263

    arr = Array.new 
    my_hash.each do |el|
      #collect them here...
      arr.push(el["sex"]);
    end

Hope it helps

Upvotes: -2

Arup Rakshit
Arup Rakshit

Reputation: 118261

[{"sex"=>"male"}, {"sex"=>"male"}, {"sex"=>"female"}].flat_map(&:values)

Upvotes: 4

tadman
tadman

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

Jokester
Jokester

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

Related Questions