From: Brian Candler Date: 2010-04-03T16:32:58+09:00 Subject: Re: hash key with multiple values Lucky Nl wrote: > puts @results > [{x=>"i8"}, {y=>"i58"}, {y=>"i6"}, {y=>"v5"}, {z=>"ci5"}, {z=>"i63"}, > {w=>"cie201"}] > [/code] > from this @results hash ,i want to get new hash like below > > [code] > puts @conver_results > [{x=>"i8"}, {y=>"i58","i6","v5"}, {z=>"ci5","i63"}, {w=>"cie201"}] > [/code] Note that {z=>"ci5","i63"} is not valid hash syntax. But you can have {"z"=>["ci5","i63"]} @conver_results = Hash.new { |h,k| h[k] = [] } @results.each { |h| h.each { |k,v| @conver_results[k] << v } } The first line makes a Hash whose elements are automatically an empty array if not already created. The second iterates over your original hashes and adds to the values array for each key. Another way: @conver_results = {} @results.heac { |h| h.each { |k,v| @conver_results[k] ||= [] @conver_results[k] << v } } -- Posted via http://www.ruby-forum.com/.