From: Robert Klemme Date: 2005-10-26T20:22:03+09:00 Subject: Re: sort on multiple attributes Terje Tjervaag 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 Btw, IMHO you should not need track_number.to_i as they should really be stored as numbers. Alternative tracks.sort do |a,b| [:artist, :album, :track_number].each do |field| c = a.send(field) <=> b.send(field) return c unless c == 0 end 0 end I have also a related RCR pending that still can make it into the std lib... http://rcrchive.net/rcr/show/293 Kind regards robert