TGR TGR - 1 year ago 51
Ruby Question

Taking values from a ruby hash

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
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?

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

Answer Source

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

=> ["Value1", "Value2", "Value3", "Value4", "Value5", "Value6"]

This is an answer on the original question.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download