9
Dec

Google Charts’ simpleEncode in Ruby

   Posted by: rew   in Programming, Ruby

I couldn’t resist. Note the is_numeric? method, which is not very pretty Ruby (I should open up a base class somewhere and put it there), but it works and is only syntactic sugar anyway, to make the simpleEncode method itself a little nicer to read.

Note that it produces slightly different output than the PHP one, namely because Ruby handles integer arithmetic a little differently, thus the round() method was not needed here. If I changed this line:

      chartData < < simpleEncoding[simpleLength * val / maxValue];

to this:

      chartData < < simpleEncoding[(simpleLength * val.to_f / maxValue).round];

the output is identical. But visually they’re nearly indistinguishable when charted, as the difference amounts to (literally) a rounding error at any given point.

def is_numeric?(arg)
  Float arg rescue false
end

def simpleEncode(values, maxValue=-1)
  simpleEncoding = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  simpleLength = simpleEncoding.size - 1

  # Just ignore any non-numeric values                                                               

  maxValue = values.select{|f| is_numeric?(f) }.max if maxValue < 0

  chartData = 's:'
  values.each do |val|
    if is_numeric?(val)
      chartData << simpleEncoding[(simpleLength * val.to_f / maxValue).round];
    else
      chartData << '_';
    end
  end
  return chartData;
end
This entry was posted on Sunday, December 9th, 2007 at 4:04 pm and is filed under Programming, Ruby. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a reply

Name (*)
Mail (will not be published) (*)
URI
Comment