Skip to content

From java processing to ruby processing

Martin Prout edited this page Apr 22, 2015 · 28 revisions

Here are some the main differences moving from vanilla processing to ruby-processing:-

  1. You do not declare types in ruby vec = PVector.new instead of PVector vec = new PVector() for example, however in this case you should prefer to use Vec2D and Vec3D, which are ruby-processing alternatives to PVector (but with methods that are much more ruby-like, and have extended functionality).

  2. There are no void methods (what's evaluated gets returned without needing an explicit return)

  3. Everything is an object (this includes primitive types float, integer etc cf. java) see more

  4. Confusing for beginners and especially pythonistas there is often more than one way to do it

  5. Processing makes heavy use of java inner classes (to make methods and values somewhat globally available) ruby-processing provides the Processing::Proxy mixin to somewhat mimic this behaviour see app.rb. An alternative to consider is to use delegator methods using extend Forwardable, requires require 'forwardable' see JRubyArt example.

In general you should try and code in regular ruby (in ruby-processing), only using processing shortcuts / methods when you need to (ie when ruby alternatives don't exist, many processing shortcuts just aren't needed in ruby). From 3. above you should use:-

  • a**b for pow(a, b)
  • theta.degrees for degrees(theta)
  • theta.radians for radians(theta)
  • x.abs for abs(x)
  • x.ceil for ceil(x)
  • x.round for round(x)
  • str.strip for trim(str)
  • str.hex for hex(str)
  • string.to_i(base=16) for unhex(str)

Other ruby methods to prefer:-

  • rand(x) to random(x)
  • rand(lo..hi) to random(lo, hi)
  • puts val (or even just p val) to println(val)
  • map1d(val, (range1), (range2)) to map(value, start1, stop1, start2, stop2)
  • (lo..hi).clip(amt) to constrain(amt, lo, hi) it is how it is implemented

The processing map(value, start1, stop1, start2, stop2) method has been implemented in ruby-processing, but is not to be confused with regular ruby map that is much used in ruby to map a function to an array ( and also in java-8 lambdas ). For example usage of map1d see reference.