[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Newbie question about nested sort

Kroeger, Simon (ext)

1/4/2006 1:37:00 PM



> From: Robert Klemme [mailto:bob.news@gmx.net]
>
> Grehom wrote:
> > what am I doing wrong? I wanted to sort primarily on count (second
> > position in array), then sub-sort alphabetically (first position in
> > array)
> >
> > char_freq = [["c", 2],["b", 5],["a", 2]]
> > sorted_freq = char_freq.sort {|a, b| b[1]<=>a[1] || a[0]<=>b[0] }
> > sorted_freq.each do |d|
> > print d[0]*d[1]
> > end
> >
> > [...]
>
> Generally you need to do conditional evaluation based on higher prio
> results. Using "||" or "or" won't help here (dunno what Perl
> does here).
>
> You want something like
> [...]

hmmm, I don't think he realy *want's* this.

Please don't scare our new perl friends away... :)
there is a simple solution to that:

char_freq = [["c", 2],["b", 5],["a", 2]]
sorted_freq = char_freq.sort {|a, b| (b[1]<=>a[1]).nonzero? ||
a[0]<=>b[0] }
sorted_freq.each do |d|
print d[0]*d[1]
end

cheers

Simon


1 Answer

Robert Klemme

1/4/2006 1:47:00 PM

0

Kroeger, Simon (ext) wrote:
>> From: Robert Klemme [mailto:bob.news@gmx.net]
>>
>> Grehom wrote:
>>> what am I doing wrong? I wanted to sort primarily on count (second
>>> position in array), then sub-sort alphabetically (first position in
>>> array)
>>>
>>> char_freq = [["c", 2],["b", 5],["a", 2]]
>>> sorted_freq = char_freq.sort {|a, b| b[1]<=>a[1] || a[0]<=>b[0] }
>>> sorted_freq.each do |d|
>>> print d[0]*d[1]
>>> end
>>>
>>> [...]
>>
>> Generally you need to do conditional evaluation based on higher prio
>> results. Using "||" or "or" won't help here (dunno what Perl
>> does here).
>>
>> You want something like
>> [...]
>
> hmmm, I don't think he realy *want's* this.
>
> Please don't scare our new perl friends away... :)

:-)))

> there is a simple solution to that:
>
> char_freq = [["c", 2],["b", 5],["a", 2]]
> sorted_freq = char_freq.sort {|a, b| (b[1]<=>a[1]).nonzero? ||
> a[0]<=>b[0] }
> sorted_freq.each do |d|
> print d[0]*d[1]
> end

I didn't think of using #nonzero? - this clearly resembles the perl
solution most. Although I'd say that I'd probably prefer the sort_by
approach with negated values...

Kind regards

robert