简体   繁体   中英

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"]

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.

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

EDIT: As directed by @tadman. Thanks!

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'] }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM