lib/geometry/size.rb in geometry-6.2 vs lib/geometry/size.rb in geometry-6.3

- old
+ new

@@ -1,7 +1,10 @@ require 'matrix' +require_relative 'size_one' +require_relative 'size_zero' + module Geometry =begin An object representing the size of something. Supports all of the familiar {Vector} methods as well as a few convenience @@ -27,17 +30,46 @@ def self.[](*array) array.map! {|a| a.respond_to?(:to_a) ? a.to_a : a } array.flatten! super *array end - + + # Creates and returns a new {SizeOne} instance. Or, a {Size} full of ones if the size argument is given. + # @param size [Number] the size of the new {Size} full of ones + # @return [SizeOne] A new {SizeOne} instance + def self.one(size=nil) + size ? Size[Array.new(size, 1)] : SizeOne.new + end + + # Creates and returns a new {SizeOne} instance. Or, a {Size} full of zeros if the size argument is given. + # @param size [Number] the size of the new {Size} full of zeros + # @return [SizeOne] A new {SizeOne} instance + def self.zero(size=nil) + size ? Size[Array.new(size, 0)] : SizeOne.new + end + # Allow comparison with an Array, otherwise do the normal thing def ==(other) return @elements == other if other.is_a?(Array) super other end + # Override Vector#[] to allow for regular array slicing + def [](*args) + @elements[*args] + end + + def coerce(other) + case other + when Array then [Size[*other], self] + when Numeric then [Size[Array.new(self.size, other)], self] + when Vector then [Size[*other], self] + else + raise TypeError, "#{self.class} can't be coerced into #{other.class}" + end + end + def inspect 'Size' + @elements.inspect end def to_s 'Size' + @elements.to_s @@ -89,17 +121,16 @@ left = right = top = bottom = 0 if 1 == args.size left = top = -args.shift right = bottom = 0 elsif 2 == args.size - left = -args.shift - top = -args.shift - right = bottom = 0 + left = right = -args.shift + top = bottom = -args.shift end - left = -options[:x] if options[:x] - top = -options[:y] if options[:y] + left = right = -options[:x] if options[:x] + top = bottom = -options[:y] if options[:y] top = -options[:top] if options[:top] left = -options[:left] if options[:left] bottom = -options[:bottom] if options[:bottom] right = -options[:right] if options[:right] @@ -123,16 +154,15 @@ left = right = top = bottom = 0 if 1 == args.size left = top = args.shift right = bottom = 0 elsif 2 == args.size - left = args.shift - top = args.shift - right = bottom = 0 + left = right = args.shift + top = bottom = args.shift end - left = options[:x] if options[:x] - top = options[:y] if options[:y] + left = right = options[:x] if options[:x] + top = bottom = options[:y] if options[:y] top = options[:top] if options[:top] left = options[:left] if options[:left] bottom = options[:bottom] if options[:bottom] right = options[:right] if options[:right]