How does Ruby's sort method work with the combined comparison (spaceship) operator?

杀马特。学长 韩版系。学妹 提交于 2020-01-01 05:23:05

问题


Beginning programmer here, just wanting to understand the process behind Ruby's sort method when using the spaceship operator <=>. Hope someone can help.

In the following:

array = [1, 2, 3]
array.sort { |a, b| a <=> b }

... I understand that sort is comparing a pair of numbers at a time and then returning -1 if a belongs before b, 0 if they're equal, or 1 if a should follow b.

But in the case of sorting in descending order, like so:

array.sort { |a, b| b <=> a }

... what exactly is happening? Does sort still compare a <=> b and then flip the result? Or is it interpreting the returns of -1, 0 and 1 with reversed behavior?

In other words, why does placing the variables in the block like so:

array.sort { |b, a| b <=> a }

...result in the same sorting pattern as in the first example?


回答1:


a <=> b will return -1 if a belongs before b, 0 if they're equal, or 1 if a should follow b.
b <=> a will return -1 if b belongs before a, 0 if they're equal, or 1 if b should follow a.

Since you are reversing the order, the output should be reversed, just like the - operator, for example. 3-5 is -2, and 5-3 is 2.

array.sort { |b, a| b <=> a } is equal to array.sort { |a, b| a <=> b } because the first argument is before the spaceship, and the second is after. Ruby doesn't care what the name of the variable is.




回答2:


Sort just does this:

comparison_block.call(elem[i],elem[j])

It doesn't know or care what your block looks like internally, but it knows which element it passed in as the first argument and which as the second, and that's what the result is based on. In a normal numeric ascending sort, calling the block with (1,0) should return 1; calling it with (0,1) should return -1. Order matters.



来源:https://stackoverflow.com/questions/16600251/how-does-rubys-sort-method-work-with-the-combined-comparison-spaceship-operat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!