From: Kyle Hunter Date: 2013-07-03T11:39:08+09:00 Subject: Implementing sort/sort! Hello, 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. class Point include Comparable attr_accessor :x, :y def initialize(x, y) @x = x @y = y end def <=>(other) x_cmp = @x <=> other.x x_cmp != 0 ? x_cmp : @y <=> other.y end end class Polygon include Enumerable attr_accessor :points alias_method :_sort, :sort def initialize(points) @points = points end def each(&blk) @points.each(&blk) end def sort Polygon.new _sort end def sort! @points = _sort end end # Example usage poly = Polygon.new [Point.new(3,4), Point.new(1,2)] poly.sort poly.sort! -- Posted via http://www.ruby-forum.com/.