Hi --

On Sun, 7 Oct 2007, Eric Hodel wrote:

> I haven't seen this technique in the wild before.
>
> If you have custom sorting using the spaceship:
>
> class Something
> def <=>(other)
>   [@name, @version] <=> [other.name, other.version]
> end
> end
>
> You can't easily use the more-efficient #sort_by because you'll need to know 
> how to sort Somethings, which involves duplication:
>
> somethings.sort_by { |s| [s.name, s.version] }
>
> Instead you can add a method that returns the thing to sort by:
>
> class Something
> def sort_obj
>   [@name, @version]
> end
>
> def <=>(other)
>   sort_obj <=> other.sort_obj
> end
> end
>
> So now using #sort_by is easy:
>
> somethings.sort_by { |s| s.sort_obj }
>
> I don't know if the name #sort_obj is appropriate, but I'm not coming up with 
> something better.

Maybe #sort_key.


David

-- 
Upcoming training from Ruby Power and Light, LLC:
   * Intro to Ruby on Rails, Edison, NJ, October 23-26
   * Advancing with Rails, Edison, NJ, November 6-9
Both taught by David A. Black.
See http://www.rubypal.com for more info!