From: "Jesús Gabriel y Galán" Date: 2009-10-02T04:38:45+09:00 Subject: Re: 2D array to array of hashes with repeating header On Thu, Oct 1, 2009 at 9:00 PM, Jason Lillywhite wrote: > Josh Cheek wrote: >> 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}] > > Thank you. I have a question about this. I tried this and accidentally > initialized the variable 'hsh' outside the map! method and could not get > the correct result. I'm curious why this is wrong: > > header = to_convert.shift > hsh = Hash.new > to_convert.map! do |ary| >  ary.each_with_index{|val,index| hsh[header[index]] = val } >  hsh > end > > to_convert # => [{:pressure=>7.56, :time=>2}, {:pressure=>7.56, > :time=>2}, {:pressure=>7.56, :time=>2}] Because in this case you are using the same object (referenced by hsh) for all iterations (map!). Map collects (:)) all results from the blocks and puts them into an array. In your case, all iterations are returning the same object (hsh), and so your resulting array contains exactly the same values in all positions: in fact they are the *same* object. You can check this with object_id. In the proposed solution a new Hash object is created for each iteration, and so each position in the resulting array is a different object. Jesus.