From: Josh Cheek Date: 2009-09-27T17:12:25+09:00 Subject: Re: 2D array to array of hashes with repeating header --000e0cd1d4aca0124c04748abd9f Content-Type: text/plain; charset=ISO-8859-1 On Sun, Sep 27, 2009 at 1:10 AM, Jason Lillywhite < jason.lillywhite@gmail.com> wrote: > I have this array: > data = [[:time, :pressure],[0,2.3],[1,4.1],[2,7.56],...] > > All the arrays in data could have an arbitrary number of items in it and > the total number of arrays in data is arbitrary but all arrays will be > the same size and the first array will always be the "header" array. > > I need to convert data to an array that looks like this: > > new_data = > > [{:time=>0,:pressure=>2.3},{:time=>1,:pressure=>4.1},{:time=>2,:pressure=>7.56}] > > Is there a straight forward way to set this up? I'm happy with hints. > Thank you! > -- > Posted via http://www.ruby-forum.com/. > > This is destructive. If you want to keep the original data too, you can implement the same process slightly differently, but this was just cleaner. to_convert = [[:time, :pressure],[0,2.3],[1,4.1],[2,7.56]] header = to_convert.shift to_convert.map! do |ary| hsh = Hash.new ary.each_with_index{|val,index| hsh[header[index]] = val } hsh end to_convert # => [{:pressure=>2.3, :time=>0}, {:pressure=>4.1, :time=>1}, {:pressure=>7.56, :time=>2}] --000e0cd1d4aca0124c04748abd9f--