# Re: stable sort\_by?

**URL:** <https://www.ruby-forum.com/t/re-stable-sort-by/53273>\
**Category:** Ruby\
**Created:** [December 13, 2005, 4:38pm UTC](https://www.ruby-forum.com/t/re-stable-sort-by/53273 "2005-12-13T16:38:35Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![KroegerS\_Simon\_Sext](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/57b2e6/32.png) [@KroegerS\_Simon\_Sext](https://www.ruby-forum.com/u/KroegerS_Simon_Sext)\
**Post date:** [December 13, 2005, 4:38pm UTC](https://www.ruby-forum.com/t/re-stable-sort-by/53273/1 "2005-12-13T16:38:35Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![KroegerS\_Simon\_Sext](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/57b2e6/32.png) [@KroegerS\_Simon\_Sext](https://www.ruby-forum.com/u/KroegerS_Simon_Sext)\
**Post date:** [December 13, 2005, 5:24pm UTC](https://www.ruby-forum.com/t/re-stable-sort-by/53273/2 "2005-12-13T17:24:43Z")

</div>

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.
