Experiments with ruby-processing (processing-2.2.1) and JRubyArt for processing-3.0

Saturday, 19 September 2009

Using Multidimensional Data Arrays



require 'ruby-processing'

class Sierpinski < Processing::App
  def setup
    size 800, 800
    ### data is an array of calculated coordinates for the Sierpinski triangle    
    data= [[[400.000000, -0.546875,387.500000, 21.103760,412.500000, 21.103760]],
    [[387.500000, 21.103760,375.000000, 42.754395,400.000000, 42.754395]],
    ####################################################################
    # Most data lines omitted
    ####################################################################
    [[787.500000, 670.622803,775.000000, 692.273438,800.000000, 692.273438]]]
    fill 0
    background 255
    no_stroke
    data.each do |line|
      line.each do |tri|
        triangle(*tri) ## use 'splat' to de-array coordinates
      end
    end
  end
end


There are some neat tricks you can use in ruby to read data from multidimensional arrays. The above code includes only a very partial amount of the data array, but the code illustrates how easy it is to extract the data from a multidimensional array in ruby. The "splat" prefix '*' strips the values out of the array, which can then be used directly to draw the triangle.  This approach may be useful if there is performance need to avoid avoid recursion overhead. There's a lot of gibberish on the web about tail recursion optimization on the way for java 7 (and hence ruby 1.9? and may'be jruby so you won't need to worry about such optimization in the future, whenever that comes).

No comments:

Post a Comment

Followers

Blog Archive

About Me

My photo
I have developed JRubyArt and propane new versions of ruby-processing for JRuby-9.1.5.0 and processing-3.2.2