(Rails) Creating multi-dimensional hashes/arrays from a data set...?
- by humble_coder
Hi All,
I'm having a bit of an issue wrapping my head around something. I'm currently using a hacked version of Gruff in order to accommodate "Scatter Plots". That said, the data is entered in the form of:
g.data("Person1",[12,32,34,55,23],[323,43,23,43,22])
...where the first item is the ENTITY, the second item is X-COORDs, and the third item is Y-COORDs.
I currently have a recordset of items from a table with the columns: POINT, VALUE, TIMESTAMP. Due to the "complex" calculations involved I must grab everything using a single query or risk way too much DB activity. That said, I have a list of items for which I need to dynamically collect all data from the recordset into a hash (or array of arrays) for the creation of the data items. I was thinking something like the following:
@h={}
e = Events.find_by_sql(my_query)
e.each do |event|
@h["#{event.Point}"][x] = event.timestamp
@h["#{event.Point}"][y] = event.value
end
Obviously that's not the correct syntax, but that's where my brain is going. Could someone clean this up for me or suggest a more appropriate mechanism by which to accomplish this? Basically the main goal is to keep data for each pointname grouped (but remember the recordset has them all).
Much appreciated.
EDIT 1
g = Gruff::Scatter.new("600x350")
g.title = self.name
e = Event.find_by_sql(@sql)
h ={}
e.each do |event|
h[event.Point.to_s] ||= {}
h[event.Point.to_s].merge!({event.Timestamp.to_i,event.Value})
end
h.each do |p|
logger.info p[1].values.inspect
g.data(p[0],p[1].keys,p[1].values)
end
g.write(@chart_file)