-2
a = [{"a":1},{"b":2}]

I want my output should be

[{ "a":1, "b":2 }]

How to do the format in ruby?

jisan
  • 33
  • 1
  • 11
  • Possible duplicate of [Array of hashes to hash](https://stackoverflow.com/questions/10943909/array-of-hashes-to-hash) – Sebastián Palma Nov 10 '18 at 02:05
  • What is your question? Do you want to merge the hashes? If so see the answer above of Sebastian. Or do you want to keep the string keys instead of symbols? Or maybe both ;) – Axe Nov 11 '18 at 13:52

1 Answers1

2

You can achieve this with:

[[{"a":1},{"b":2}].inject(:merge)]
# => [{:a=>1, :b=>2}] 

Which iterates over the array and merges each hash, then closes it all in an array. I really doubt you need to close your hash in an array as the last step though.

Marcin Kołodziej
  • 5,253
  • 1
  • 10
  • 17