On 26/10/05, Terje Tjervaag <flecktone / gmail.com> wrote: > Hi, > > Just thought I'd write this to the list, since it wasn't immediately > obvious to me how to do it and I couldn't find it written anywhere on > the web.. > > Say you have an array of these music tracks: > Track = Struct.new("Track", :name, :artist, :album, :track_number) > > ..and you want to sort the array first by artist, then by album within > that artist and finally by track number within the album, this can > still be done by a pretty neat sort block: > > sorted_tracks = tracks.sort do |a,b| > if a.artist != b.artist > a.artist <=> b.artist > elsif a.album != b.album > a.album <=> b.album > else > a.track_number.to_i <=> b.track_number.to_i > end > end > > -- > Terje > > Or you can say sorted_tracks = tracks.sort_by { | track | [track.artist, track.album, track.track_number] } or even: class Array def sort_by_att(*attributes) attributes = attributes.flatten self.sort_by { | e | attributes.map { | a | e.send(a) } } end end sorted_tracks = tracks.sort_by_att(:artist, :album, :track_number) (warning, untested code, beware of the bug) regards, Brian -- http://ruby.brian-schroeder.de/ Stringed instrument chords: http://chordlist.brian-schroeder.de/