0

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.

3
  • Actually you don't have a ruby hash in a, you have an array of hashes in a. Commented May 27, 2016 at 8:10
  • do you want an array of arrays, or just a single array of all the values? Commented May 27, 2016 at 8:13
  • 1
    Maybe you want this? [["Value1", "Value2"], ["Value3", "Value4"], ["Value5", "Value6"]] (Just modify Ilya's answer to use map instead of flat_map) Commented May 27, 2016 at 8:14

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Or even more shorter: a.flat_map(&:values)
Perfect and this is the output I wanted. Thanks a lot for your lightning response :)
@TGR this is basically the output you had in your original question, why did you change it?
@Stefan I was little confused. Apols for confusion. I am perfectly fine with llya & Sergil's output

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.