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:
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:
data = [[:time, :pressure],[0,2.3],[1,4.1],[2,7.56],...]
axes = data.shift #shift the axes labels out from the data set
new_data = data.collect{|point| {axes[0] => point[0], axes[1] => point
[1]}} #pair the axes with the data by iterating and collecting the
results
Tim
···
On Sep 26, 11:10 pm, Jason Lillywhite <jason.lillywh...@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:
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
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.
···
On Thu, Oct 1, 2009 at 9:00 PM, Jason Lillywhite <jason.lillywhite@gmail.com> wrote:
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