-2

I have a hash called hash1

hash1 = [{key: 'key1', value: 'value1'}, {key: 'key2', value: 'value2'}, {key: 'key3', value: 'value3'}]

And want to convert to below format

{'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3'}
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Vinay
  • 324
  • 1
  • 3
  • 15
  • 2
    BTW, `hash1` is a misleading variable name, because it is an array, not a hash. If you want to have "hash" in the name, use the plural: `hashes` – Stefan Apr 21 '17 at 12:53
  • Presumably, the values of `:key` are unique, as you have not said what is wanted when, say, `hash1 = [{key: "key", value: 'value1'}, {key: "key", value: 'value2'}]`. – Cary Swoveland Apr 21 '17 at 16:00
  • Please read "[ask]" including the linked pages, "[mcve]" and "[How much research effort is expected of Stack Overflow users?](http://meta.stackoverflow.com/questions/261592)". We'd like to see evidence of your effort. What did you try? Did you search and not find anything? Did you find stuff but it didn't help? Did you try writing code? If not, why? If so, what is the smallest code example that shows what you tried and why didn't it work? Without that it looks like you didn't try and want us to write it for you. – the Tin Man Apr 21 '17 at 20:53

1 Answers1

5

If the nested hashes in hash1 always have exactly a :key and a :value key in that order, you can convert their values to a hash via Array#to_h:

hash1.map(&:values).to_h
#=> {"key1"=>"value1", "key2"=>"value2", "key3"=>"value3"}

But I'd rather be a little more explicit:

hash1.map { |h| h.values_at(:key, :value) }.to_h
#=> {"key1"=>"value1", "key2"=>"value2", "key3"=>"value3"}
Stefan
  • 109,145
  • 14
  • 143
  • 218