So, I’m was playing around with the sort method in irb with a basic
array. I noticed the array gets sorted low to high if .sort is called.
But, if I pass a block of code and use <=>, it goes high to low insead.
Here is an example:
array=[1, 5, 15, 10]
array.sort
>>[1, 5, 10, 15]
array.sort{|x, y| y<=>x}
>>[15, 10, 5, 1]
I am really confused by this. First, I got the sort and passing block
example from ruby docs. So, I am just completely confused by what is
going on in the second thing.
I understand that sort is being passed a block of code. Beyond that I
am confused.
Can someone explain why there are x and y being passed to that block (or
why it is needed between the || symbols)? Also, what does the <=> do
that makes it do the opposite of sort?
I understand that a<=>b returns 1 if a > b, 0 if a==b, and -1 if a<b.
Other than that, I don’t know why that translates to it going highest to
lowest.
Thanks for any help.