Ruby的sort方法如何与组合比较(飞船)运算符一起工作? [英] How does Ruby's sort method work with the combined comparison (spaceship) operator?

查看:79
本文介绍了Ruby的sort方法如何与组合比较(飞船)运算符一起工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是程序员,只是想了解使用飞船运算符<=>时Ruby sort方法背后的过程.希望有人能帮忙.

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

以下:

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

...我知道sort一次比较一对数字,然后如果ab之前属于-1,则返回-1;如果相等,则返回0,否则返回1如果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 }

...到底是什么情况? sort仍然会比较a <=> b,然后翻转结果吗?还是用相反的行为解释-101return?

... 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?

推荐答案

a <=> b如果ab之前属于-1,则返回-1;如果0相等,则返回1;如果1,则返回1 c4>应该紧跟b.
如果ba之前属于b <=> a将返回-1;如果相等,则返回1;如果b应该在a之后,则返回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.

由于要颠倒顺序,因此应该颠倒输出,例如像-运算符一样. 3-5-25-32.

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 }等于array.sort { |a, b| a <=> b },因为第一个参数在飞船之前,第二个参数在飞船之后. Ruby不在乎变量的名称是什么.

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.

这篇关于Ruby的sort方法如何与组合比较(飞船)运算符一起工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆