Vector Classes and Duck Typing
Duck Typing and Vector classes
Since JRubyArt-1.4.5, Vec2D and Vec3D classes support duck-typing copy constructors. This means that the source vector need only supply accessor methods for :x
and :y
(that return either float or fixnum). Note :z
can be supplied for Vec3D constructor, else z
is set to zero, however supply z
to Vec2D constructor it will be ignored see below:-
Vector = Struct.new(:x, :y) # simple valid duck-type
fred = Vector.new(1, 4)
ted = Vec2D.new(fred)
ted.inspect
# "Vec2D(x = 1.0000, y = 4.0000)"
ted3 = Vec3D.new(fred)
ted3.inspect
# "Vec3D(x = 1.0000, y = 4.0000, z = 0.0000)"
bob = Vec2D.new(ted3)
bob.inspect
# Vec2D(x = 1.0000, y = 4.0000)
Vector3 = Struct.new(:x, :y, :z) # simple valid duck-type
fred3 = Vector.new(8.0, 7.0, 10)
bob3 = Vec3D.new(fred3)
bob3.inspect
# Vec3D(x = 8.0000, y = 7.0000, z = 10.0000)
Note despite fixnum entry Vec2D and Vec3D values are stored as float (well actually as a java double, but that’s an implementation detail)