From: Joel VanderWerf Date: 2007-09-13T04:20:24+09:00 Subject: Re: Merge an array of hashes 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} -- vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407