Help required on sorting

Hi All,

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.

Tried adding a position to each of it as High -> 1 Medium -> 2 etc. and
then sorting by the position…but seems like too much of work

Any quicker way to do this?

Hi,

Am Donnerstag, 09. Jul 2009, 18:46:40 +0900 schrieb Dipti Iyengar:

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.

ary.sort_by { |elem|
case elem.risk
when /high/i then 5
when /medium/i then 4
when /low/i then 3
when /info/i then 2
when /safe/i then 1
else 0
end
}

Bertram

Hi –

On Thu, 9 Jul 2009, Dipti Iyengar wrote:

Any quicker way to do this?
You could do:

LEVELS = %w{ High Medium Low Info Safe }

sorted = risks.sort_by {|r| LEVELS.index(r.capitalize) }

David

David A. Black wrote:

Hi –

On Thu, 9 Jul 2009, Dipti Iyengar wrote:

Any quicker way to do this?
You could do:

LEVELS = %w{ High Medium Low Info Safe }

sorted = risks.sort_by {|r| LEVELS.index(r.capitalize) }

David

Thanks a lot Bertram … Worked like a charm…
Thanks a lot David…didn’t try the solution as yet :slight_smile:

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.

Bertram

David A. Black wrote:

Tried adding a position to each of it as High -> 1 Medium -> 2 etc. and
then sorting by the position…but seems like too much of work

Any quicker way to do this?

You could do:

LEVELS = %w{ High Medium Low Info Safe }

sorted = risks.sort_by {|r| LEVELS.index(r.capitalize) }

If there are a lot of levels, it might be more efficient to avoid the
linear search and use a hash. It’s not necesarily faster in this case
with only 6 levels, but anyway…

LEVELS = %w{ High Medium Low Info Safe }
LEVEL_HASH = LEVELS.inject({}) {|h, lev| h[lev] = LEVELS.index(lev); h}

risks = LEVELS + LEVELS

sorted = risks.sort_by {|r| LEVEL_HASH[r.capitalize] }
p sorted

Hi –

On Thu, 9 Jul 2009, Bertram S. wrote:

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

:slight_smile:

David