JP Silvashy
JP Silvashy

Reputation: 48555

Ruby, fast array manipulation when rendering to page

So I have some big arrays that need to be output to my views as JavaScript arrays, I'm sure this is a pretty typical challange, but say I have the following ruby object:

[
  {"timestamp"=>2011-09-07 20:45:00 UTC, "count"=>425.0}, 
  {"timestamp"=>2011-09-07 21:00:00 UTC, "count"=>4552.0}, 
  {"timestamp"=>2011-09-07 21:15:00 UTC, "count"=>4510.0}
]

but I need to transform it and render it to my views in my JS like so:

[
  [Date.UTC(2011,09,07,20,45,00),425.0],
  [Date.UTC(2011,09,07,21,00,00),4552.0],
  [Date.UTC(2011,09,07,21,15,00),4510.0]
];

What is the fastest way to do this? Is there already like a builder I can use or something? My biggest concern for something like this is the time it'll take to build the html because the arrays are sometimes pretty big.

Upvotes: 0

Views: 200

Answers (2)

tadman
tadman

Reputation: 211740

When you're faced with transforming one array into another, you might want to just use map and do it that way:

require 'time' # Required for Time.parse, unnecessary otherwise

input = [
  {"timestamp"=>Time.parse('2011-09-07 20:45:00 UTC'), "count"=>425.0}, 
  {"timestamp"=>Time.parse('2011-09-07 21:00:00 UTC'), "count"=>4552.0}, 
  {"timestamp"=>Time.parse('2011-09-07 21:15:00 UTC'), "count"=>4510.0}
]

result = input.map do |v|
  "[Date.UTC(%s), %.1f]" % [ v['timestamp'].strftime('%Y,%m,%d,%H,%M,%S'), v['count'] ]
end

puts "[\n  " + result.join(",\n  ") + "\n]"

The Enumerable module is full of useful utility methods of this variety.

Upvotes: 2

christianblais
christianblais

Reputation: 2458

You don't have the choice, you'll have to go through your array to collect the data. But, from what I can see here, it's only a matter of collecting the values of hashes in you array.

array.map(&:values)

I don't really understand your concern here... Did I miss something?

Upvotes: 2

Related Questions