Using Struct in JRubyArt
If you are coming to JRubyArt from vanilla processing, you may not be aware of ruby Struct
, which is an extremly useful way to add structure to data, and can often be used as lighweight alternative to a class eg as replacement for a 2D or 3D Vector class see below:-
Vect = Struct.new(:x, :y)
origin = Vect(0, 0)
In two lines we have created a new Struct
, Vect
and created an instance origin
of Vect
. This is the usual way of doing but you may also come across the more verbose form:-
class Vect < Struct.new(:x, :y)
end
origin = Vect.new(0, 0)
see simple vector example and a more complicated Turtle example
But ruby is so versatile we can even add a method
to our Struct
to create for example a lightweight Boundary class (which can be very useful in JRubyArt sketches):-
Boundary = Struct.new(:lower, :upper) do
def include?(x)
(lower...upper).cover? x
end
end
see fern.rb for example usage of our lightweight boundary class.
But there is more, you could use Struct within a factory module to create anonymous data types (but with a particular interface) see below:-
# Hair factory can create anonymous instances of Hair Struct
module HairFactory
Hair = Struct.new(:z, :phi, :len, :theta)
def self.create_hair(radius)
z = rand(-radius..radius)
phi = rand(0..Math::PI * 2)
len = rand(1.15..1.2)
theta = Math.asin(z / radius)
Hair.new(z, phi, len, theta)
end
end
see esfera.rb for example usage of our HairyFactory module.
You may also be interested in the even more versatile OStruct
, that takes hash args, but in practice I usually find myself creating a regular ruby class instead.