From: Phrogz Date: 2007-09-13T06:10:09+09:00 Subject: Re: Merge an array of hashes On Sep 12, 1:20 pm, Joel VanderWerf wrote: > Luis Parravicini wrote: > > On 9/12/07, cleaner416 wrote: > >> For some reason I can't get my head wrapped around this trivial > >> exercise. I have an array of hashes like so > > >> a = [ { :some_key => :some_value }, { :another_key > >> => :another_value } ] > > >> And I would like to flatten it to single hash in one line so I get > > >> { :some_key => :some_value, :another_key => :another_value } > > >> Any suggestions? > > > hash = Hash.new > > a.each { |h| hash.merge! h } > > Or the equivalent using #inject, if you like: > > a = [ { :some_key => :some_value }, { :another_key => :another_value } ] > > merged = a.inject({}) {|acc, h| acc.merge! h} > > p merged # ==> {:some_key=>:some_value, :another_key=>:another_value} ...which brings us back (almost) to JEGII's original response :) On Sep 12, 12:59 pm, James Edward Gray II wrote: > Sure: > > >> a = [{:some_key => :some_value}, {:another_key => :another_value}] > => [{:some_key=>:some_value}, {:another_key=>:another_value}] > >> a.inject { |all, h| all.merge(h) } > => {:some_key=>:some_value, :another_key=>:another_value}