传递块时 Array#sort 如何工作? [英] How does Array#sort work when a block is passed?

查看:37
本文介绍了传递块时 Array#sort 如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在理解 array.sort{ |x,y| 的方式时遇到问题块 } 完全有效,因此如何使用它?

I am having a problem understanding how array.sort{ |x,y| block } works exactly, hence how to use it?

来自 Ruby 文档的示例:

   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 }

如您所知,要对数组进行排序,您需要能够比较其元素(如果您对此表示怀疑,请尝试实现任何排序算法而不使用任何比较,不要 <><=>=).

As you know, to sort an array, you need to be able to compare its elements (if you doubt that, just try to implement any sort algorithm without using any comparison, no <, >, <= or >=).

您提供的块实际上是一个函数,sort 算法将调用该函数来比较两个项目.也就是说,xy 将始终是 sort 算法在执行过程中选择的输入数组的某些元素.

The block you provide is really a function which will be called by the sort algorithm to compare two items. That is x and y will always be some elements of the input array chosen by the sort algorithm during its execution.

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

The sort algorithm will assume that this comparison function/block will meet the requirements for method <=>:

  • 如果 x <,则返回 -1y
  • 如果 x = y 则返回 0
  • 如果 x > y 则返回 1

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

Failure to provide an adequate comparison function/block will result in array whose order is undefined.

你现在应该明白为什么了

You should now understand why

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

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

以相反的顺序返回相同的数组.

return the same array in opposite orders.

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

To elaborate on what Tate Johnson added, if you implement the comparison function <=> on any of your classes, you gain the following

  1. 你可以在你的类中包含模块Comparable,它会自动为你定义以下方法:between?==>=<<=>.
  2. 现在可以使用对 sort 的默认调用(即不带参数)对类的实例进行排序.
  1. You may include the module Comparable in your class which will automatically define for you the following methods: between?, ==, >=, <, <= and >.
  2. Instances of your class can now be sorted using the default (ie without argument) invocation to sort.

请注意,<=> 方法已经在 ruby​​ 标准库(BignumArrayFile::StatFixnumStringTime 等等.

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

这篇关于传递块时 Array#sort 如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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