我很难理解array.sort{ |x,y| block }到底是如何工作的,因此如何使用它?

Ruby documentation中的一个例子:

   a = [ "d", "a", "e", "c", "b" ]
   a.sort                     #=> ["a", "b", "c", "d", "e"]
   a.sort { |x,y| y <=> x }   #=> ["e", "d", "c", "b", "a"]

推荐答案

在你的例子中

a.sort

相当于

a.sort { |x, y| x <=> y }

正如您所知,要对数组进行排序,您需要能够比较它的元素(如果您对此有疑问,只需try 实现任何排序算法,而不使用任何比较,no <><=>=).

您提供的块实际上是一个函数,sort算法将调用它来比较两个项目.That is 101 和 102 will always be some elements of the input array chosen by the 100 algorithm during its execution.

sort算法将假设该比较函数/块将满足方法<=>的要求:

  • 如果x<;返回-1;Y
  • 如果x=y,则返回0
  • return 1 if x > y

未能提供足够的比较函数/块将导致数组的顺序未定义.

你现在应该明白为什么了

a.sort { |x, y| x <=> y }

a.sort { |x, y| y <=> x }

以相反的顺序返回同一array.


为了详细说明Tate Johnson添加的内容,如果在任何类上实现比较函数<=>,您将获得以下结果

  1. You may include the module Comparable in your class which will automatically define for you the following methods: between?, ==, >=, <, <=>.
  2. 现在可以使用默认(即无参数)调用将类的实例排序为sort.

Note that the <=> method is already provided wherever it makes sense in ruby's st和ard library (Bignum, Array, File::Stat, Fixnum, String, Time, etc...).

Ruby相关问答推荐

在 Ruby 中,如何从派生类中重写同一方法的不同方法调用基类方法?

Ruby - 使用索引值识别和更新数组中的重复项

有没有更好的方法来加入剩余不变的子列表?

这是一个很好的测试?规范

Ruby注入daisy链?

如何在 ruby​​ 中通过 SSL 调用 HTTP POST 方法?

Symfony 2assets资源过滤器异常中的指南针

为什么 Rake 不能连续调用多个任务?

什么是 '?-mix' 在 Ruby 正则表达式中

方法应该以 (?问号)结尾吗?只返回一个布尔值?

无法在 Heroku 教程中使用 Python 启动工头

如何以不同 colored颜色 输出我的 ruby​​ 命令行文本

在 ruby​​ 中访问嵌套哈希的元素

Vagrant - 如何拥有特定于主机平台的配置步骤

你能用 Ruby 开发原生 iPhone 应用程序吗?

确定Ruby的位置

Ruby CSV - 获取当前行/行号

在本地覆盖 Vagrant 配置设置(每个开发人员)

如何使用#{variable}在Ruby中格式化带有浮点数的字符串?

通过多个分隔符拆分字符串