A place for my personal musings, about programming, design or whatever come across my mind

Sorting Array

a = [9,5,6,3,7]
a.sort { |x,y| x==5? 1:x<=>y }
[3, 6, 7, 9, 5]

So, I sort the array consisting 9,5,6,3,7, run it through a block, put the elements to x and y then sort it in ascending order, except for the number “5”, which will be stuck at the end of the order.

But why in the case below then the number “2” which should be at the end of the order is instead at the second last place?

c = [22,77,88,55,44,11,2,8]
c.sort { |x,y| x==2? 1:x<=>y }
[8, 11, 22, 44, 55, 77, 2, 88]

I tried to sort a few different arrays, and sometimes the second case just pop up, which still puzzling me. Why the different?

2 Comments
Pierre Riteau
Pierre Riteau

It’s because the comparison between 2 and 88 happens with x = 88 and y = 2.

You need to correct your code with something like this:

c.sort { |x,y| x==2? 1: (y==2? -1: xy) }

kahfei
kahfei

Thanks Pierre. Guess the comparison operator is somehow missing in your comment, think you mean

c.sort { |x,y| x==2? 1: (y==2? -1: x<=>y) }

Yupe, it works. 🙂
Though I still try to understand why when it is comparing 88 and 2 that y=2, x=88 which cause this problem, and not happening in other numbers.
I think I would first needs to understand more how the array is passed to x,y| to better comprehend this.

Leave A Comment