Forum: Ruby Re: stable sort_by?

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 2005-12-13 16:38
(Received via mailing list)
I guess you have to use sort instead of sort_by in such a case,
like:

test = [[1, 'b'], [1, 'c'], [1, 'a'], [0, 'a']]

#sort for first item, than for second in reverse order
p test.sort{|a, b|(a[0] <=> b[0]).nonzero? || (b[1] <=> a[1]) }

=>[[0, "a"], [1, "c"], [1, "b"], [1, "a"]]

cheers

Simon
357558a6682f4d6624594763d9acdb35?d=identicon&s=25 Mike Fletcher (fletch)
on 2005-12-13 17:24
Kroeger, Simon (ext) wrote:
> I guess you have to use sort instead of sort_by in such a case,
> like:
>
> test = [[1, 'b'], [1, 'c'], [1, 'a'], [0, 'a']]
>
> #sort for first item, than for second in reverse order
> p test.sort{|a, b|(a[0] <=> b[0]).nonzero? || (b[1] <=> a[1]) }
>
> =>[[0, "a"], [1, "c"], [1, "b"], [1, "a"]]
>

Aaah, it's chaining with nonzero? (since it'll return the -1 or 1 if
that's the case) that I was missing.

Thanks.
This topic is locked and can not be replied to.