« Return to Thread: Help required on sorting

Re: Help required on sorting

by David A. Black :: Rate this Message:

Reply to Author | View in Thread

Hi --

On Thu, 9 Jul 2009, Bertram Scharpf wrote:

> Hi,
>
> Am Donnerstag, 09. Jul 2009, 19:11:46 +0900 schrieb David A. Black:
>> On Thu, 9 Jul 2009, Dipti Iyengar wrote:
>>>   I ve to sort risks by "High" "Medium" "Low" "Info" and "Safe"
>>>
>>> When I sort in the model it sorts in the alphabetical order which is not
>>> what i want.
>>
>>   LEVELS = %w{ High Medium Low Info Safe }
>>   sorted = risks.sort_by {|r| LEVELS.index(r.capitalize) }
>
> Gosh, this is cool! I'm ashamed of my poor case approach.

It comes from years of Ruby training where I use a deck of cards as
one of the main examples:

   RANKS = %w{ 2 3 4 5 6 7 8 9 10 j q k a }

   def <=>(other)
     RANKS.index(rank) <=> RANKS.index(other.rank)
   end

:-)


David

--
David A. Black / Ruby Power and Light, LLC
Ruby/Rails consulting & training: http://www.rubypal.com
Now available: The Well-Grounded Rubyist (http://manning.com/black2)
Training! Intro to Ruby, with Black & Kastner, September 14-17
(More info: http://rubyurl.com/vmzN)

 « Return to Thread: Help required on sorting