Array of hashes to hash

RubyArraysHash

Ruby Problem Overview


For example, I have array of single hashes

a = [{a: :b}, {c: :d}]

What is best way to convert it into this?

{a: :b, c: :d}

Ruby Solutions


Solution 1 - Ruby

You may use

a.reduce Hash.new, :merge

which directly yields

{:a=>:b, :c=>:d}

Note that in case of collisions the order is important. Latter hashes override previous mappings, see e.g.:

[{a: :b}, {c: :d}, {e: :f, a: :g}].reduce Hash.new, :merge   # {:a=>:g, :c=>:d, :e=>:f}

Solution 2 - Ruby

You can use .inject:

a.inject(:merge)
#=> {:a=>:b, :c=>:d}

Demonstration

Which initiates a new hash on each iteration from the two merged. To avoid this, you can use destructive :merge!( or :update, which is the same):

a.inject(:merge!)
#=> {:a=>:b, :c=>:d}

Demonstration

Solution 3 - Ruby

These two are equivalent:

total_hash = hs.reduce({}) { |acc_hash, hash| acc_hash.merge(hash) }
total_hash = hs.reduce({}, :merge)

Note that Hash#merge creates a new hash on each iteration, which may be a problem if you are building a big one. In that case, use update instead:

total_hash = hs.reduce({}, :update)

You can also convert the hashes to pairs and then build the final hash:

total_hash = hs.flat_map(&:to_a).to_h

Solution 4 - Ruby

I came across this answer and I wanted to compare the two options in terms of performance to see which one is better:

  1. a.reduce Hash.new, :merge
  2. a.inject(:merge)

using the ruby benchmark module, it turns out that option (2) a.inject(:merge) is faster.

code used for comparison:

require 'benchmark'

input = [{b: "c"}, {e: "f"}, {h: "i"}, {k: "l"}]
n = 50_000

Benchmark.bm do |benchmark|
  benchmark.report("reduce") do
    n.times do
      input.reduce Hash.new, :merge
    end
  end

  benchmark.report("inject") do
    n.times do
      input.inject(:merge)
    end
  end
end

the results were

       user     system      total        real
reduce  0.125098   0.003690   0.128788 (  0.129617)
inject  0.078262   0.001439   0.079701 (  0.080383)

Solution 5 - Ruby

Just use

a.reduce(:merge)
#=> {:a=>:b, :c=>:d}

Solution 6 - Ruby

Try this

a.inject({}){|acc, hash| acc.merge(hash)} #=> {:a=>:b, :c=>:d}

Solution 7 - Ruby

You can transform it to array [[:a, :b]] and after that translate everything to hash {:a=>:b}

# it works like [[:a, :b]].to_h => {:a=>:b}

[{a: :b}, {c: :d}].map { |hash| hash.to_a.flatten }.to_h

# => {:a=>:b, :c=>:d}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionevfwcqcgView Question on Stackoverflow
Solution 1 - RubyHowardView Answer on Stackoverflow
Solution 2 - RubypotashinView Answer on Stackoverflow
Solution 3 - RubytoklandView Answer on Stackoverflow
Solution 4 - RubybigsolomView Answer on Stackoverflow
Solution 5 - RubyRitesh katareView Answer on Stackoverflow
Solution 6 - RubyRahul PatelView Answer on Stackoverflow
Solution 7 - RubyVlad HilkoView Answer on Stackoverflow