I was wondering about implementing sort/sort!. Basically, I have a Point
class, which contains x, y variables of a 2d Cartesian point. It also
includes the Comparable mixin and thus implements a <=> method.
I also have a Polygon class which is really just a container for an
array of the aforementioned Point class. I guess the name is a misnomer
but I’m working on adding functionality. Anyway, I want Polygon.sort to
return a new Polygon with the points sorted, and Polygon.sort! to modify
the points inside of the current polygon.
I’ve attempted it, and it seems to work, but I was wondering if anyone
could recommend a more canonical or idiomatic way to do it, or point out
any flaws with my approach.
attr_accessor :x, :y
def initialize(x, y)
@x = x
@y = y
x_cmp = @x <=> other.x
x_cmp != 0 ? x_cmp : @y <=> other.y
alias_method :_sort, :sort
@points = points
@points = _sort
poly = Polygon.new [Point.new(3,4), Point.new(1,2)]