From: Brian Candler Date: 2011-04-21T18:41:29+09:00 Subject: Re: Using the spaceship operator RichardOnRails wrote in post #994206: > Class MyTest < Array > def <=>(other) > self[1] <=> other[1] > end > > @sorted_array = $date > end > > How can I make this work? Your way *can* be made to work, but it's ugly. class MyElement < Array def <=>(other) self[1] <=> other[1] end end a = [ MyElement.new([:A,12]), MyElement.new([:B,30]), MyElement.new([:C,4]), ] a.sort! p a The point is that the <=> operator is applied to pairs of elements in the array, not to the container object itself. As a general rule I'd say: don't subclass standard Ruby classes. Use delegation instead. So if you want a container object with Array-like properties but special behaviour, then make it have an Array, rather than be an Array. class MyContainer def initialize(a = []) @a = a end def sort! @a = @a.sort_by { |elem| elem[1] } end ... delegate other methods as required, ... or use SimpleDelegator end In the longer term you'll find this a much more flexible way of composing objects and behaviour. The only reason programming classes tell you to subclass is because of the inflexible typing systems in certain other languages. Ruby has "duck typing": there is no need for your class to inherit from Array, it just has to implement the behaviour of Array that you're interested in. -- Posted via http://www.ruby-forum.com/.