Forum: Ruby Re: Newbie question about nested sort

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
87e9a89c53ccf984db792113471c2171?d=identicon&s=25 Kroeger, Simon (ext) (Guest)
on 2006-01-04 14:37
(Received via mailing list)
> >    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
5befe95e6648daec3dd5728cd36602d0?d=identicon&s=25 Robert Klemme (Guest)
on 2006-01-04 14:49
(Received via mailing list)
Kroeger, Simon (ext) wrote:
>>>    print d[0]*d[1]
>
> 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
This topic is locked and can not be replied to.