Welcome to Working With Rails

 

Discussion Forums

Discuss all things Ruby on Rails with perhaps the web's most vibrant group of Ruby on Rails enthusiasts.
Creating multi-dimensional hashes/arrays from a data set...?
2 Posts
Creating multi-dimensional hashes/arrays from a data set...?

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.

I do not know if I understood your question right, but I think this may help you:
e = Events.find_by_sql(my_query)
h = Hash.new

e.each do |event|
  h[event.point] => { :timestamp => event.timestamp, :value => event.value }
end

Now you can access the hash of the following ways: 
h[a_point] return { :timestamp => a_timestamp, :value => a_value }
h[a_point][:timestamp] return a_timestamp
h[a_point][:value] return a_value

I hope that has helped.

2 Posts
Login to add your message