From: RichardOnRails Date: 2011-04-21T22:50:35+09:00 Subject: Re: Using the spaceship operator On Apr 21, 12:13 am, RichardOnRails wrote: > Hi, > > Here an abstract version of my app, in which I have an array of two- > element arrays I'd like to sort on the second element of each pair > using the spaceship operator: > > $data = [ [:A, 12], [:B, 30], [:C, 4] ] > > Class MyTest < Array >     def <=>(other) >         self[1] <=> other[1] >     end > >     @sorted_array = $date >  end > > How can I make this work? > > Thanks in advance, > Richard Hi John and Brian, Thank you very much for your extremely insightful answers. I've been oscillating between: Metaprogramming Ruby The Well-Oriented Rubyist Design Patterns in Ruby But I didn't see anything in them for my sorting problem, so I Googled for it. Thus I found this concise method, but I couldn't figure out how to make "self" be my array of arrays. John: Thanks for that sort_by method using a block to return the specific value (from each element) I want the sort method to use. Very tidy! Brian: Thanks for 1. addressing my key issue about how to make "self" be my array, so to speak. Question, would that redefinition of <=> contaminate uses of "sort" in other top-level classes? I could test for an answer, but I might miss something. 2. using "delegation", which I've seen in those textbooks but not yet internalized. Best wishes, Richard