简体   繁体   中英

Taking values from a Ruby array of hashes

I have an array of hashes:

a = [{"Key1"=>"Value1", "Key2"=>"Value2"}, 
     {"Key1"=>"Value3", "Key2"=>"Value4"},
     {"Key1"=>"Value5", "Key2"=>"Value6"}]

Basically I am trying to get an output with only values and not any keys. Something like this

['Value1', 'Value2', 'Value3', 'Value4', 'Value5', 'Value6']

Here is the code which I tried. As key1 and key2 are the same, I stored both the keys in an array....

k = ["key1", "key2"]
for i in 0..a.length  
  k.each do |key_to_delete| 
    a[i].delete key_to_delete unless a[i].nil?
  end 
end

However, this removes all values and I get an empty array. Any help is appreciated.

You can use Enumerable#flat_map and fetch values from each hash:

a.flat_map(&:values)
=> ["Value1", "Value2", "Value3", "Value4", "Value5", "Value6"]

This is an answer on the original question.

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