新手问题 sort 方法里 block 的 a 和 b,两个参数是指什么?

drine · 2015年01月03日 · 最后由 piecehealth 回复于 2015年01月03日 · 1796 次阅读

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

不知道 a 和 b 的意思是什么。 而且不知道怎么单独测试每一次排序后的输出结果... 不知道怎么写 block 里的具体规则

求指南下

或者 sort 的 block 里只能规定按 a<=>b 或者 b<=>a 执行?不能自己定义正则表达式什么吗?

文档里也没有说到 block 里的具体意思...

http://www.ruby-doc.org/core-2.2.0/Array.html#method-i-sort

Comparisons for the sort will be done using the <=> operator or using an optional code block.

The block must implement a comparison between a and b, and return -1, when a follows b, 0 when a and b are equivalent, or +1 if b follows a.

需要 登录 后方可回复, 如果你还没有账号请 注册新账号