From: Brian Mattern Date: 2006-03-09T00:25:26+09:00 Subject: Re: Newbie: sorting an array of custom objects On Wednesday 08 March 2006 08:48, Einar H淡st wrote: > > That solution requires some_field to be 'naturally' ordered, though, > doesn't it? (I'm very new to Ruby...) What if some_field contains a > string, and I want 'Oranges' to be sorted before 'Apples'? Actually, I'm > writing a card game, so I want 'Spades' < 'Hearts' < 'Clubs' < 'Diamonds'. > > - Einar Ideally you would have a Card class that has value and suit fields. Then you could implement <=> and just use Array#sort. Alternatively, if you want to sort a specific way just the one time, you can pass a block to sort which takes two parameters |a,b| and returns -1 if a < b, 0 if a == b and 1 if a >b. So, you could do something like: #an array of suit strings SUITS = %w{Spades Hearts Clubs Diamonds} # use a simple array for each card for this example cards = [[3, 'Clubs'], [2, 'Spades'], [10, 'Diamonds'], [5, 'Clubs'], [7, 'Hearts']] sorted = cards.sort { |a, b| ord = SUITS.index(a.last) <=> SUITS.index(b.last) #sort by suit ord = a.first <=> b.first if ord = 0 #suit matched, so sort value ord } #print out the cards in sorted order puts sorted.map{ |card| "#{card.first} of #{card.last}" }.join(', ') -- Brian Mattern