TGR TGR - 6 months ago 8
Ruby Question

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.

Answer

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.

Comments