如何数组排序#工作的时候块传递? [英] How does Array#sort work when a block is passed?

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

问题描述

我有理解的一个问题是如何中的Array.sort {| X,Y |块} 的工作原理完全,因此,如何使用它?

文档一个例子:

  A = [D,A,E,C,B]
   a.sort#=> [一,B,C,D,E]
   a.sort {| X,Y | Y'LT; = GT; X}#=> [E,D,C,B,A]


解决方案

在您的例子

  a.sort

等同于

  a.sort {| X,Y | X'LT; = GT; ÿ}

如你所知,排序一个数组,你需要能够比较的元素(如果你怀疑,只是试图实现任何排序算法,而无需使用任何比较,没有< > < = > = )。

您提供的块确实是一个将由被称为排序算法来比较两个项目的功能。 这就是 X 将永远是由<$ C $选择输入数组中的某些元素C>排序在执行过程中的算法。

排序算法假定这个比较函数/块将符合法的要求&LT; =&GT;


  • 返回-1如果x&LT;是

  • 返回0,如果X = Y

  • 返回1,如果X> Y

未能提供充分的比较函数/块将导致数组,其顺序是不确定的。

您现在应该明白为什么

  a.sort {| X,Y | X'LT; = GT; ÿ}

  a.sort {| X,Y | Y'LT; = GT; X }

在相反的顺序返回相同的阵列。


要阐述什么泰特约翰逊补充说,如果实现了比较功能&LT; =&GT; 在任何类中,您将获得以下


  1. 您可以包括模块可比在你的类,它会自动为您定义以下方法:?之间的 == &GT; = &LT; &LT; = 方式&gt;

  2. 您的类的实例现在可以使用默认的排序(即没有参数)调用到排序

请注意,&LT; =&GT; 已提供的方法无论它在Ruby的标准库(有道理 Bignum的阵列文件::统计 Fixnum对象字符串时间,等...)。

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

An example from 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"]

解决方案

In your example

a.sort

is equivalent to

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 >=).

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.

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

  • return -1 if x < y
  • return 0 if x = y
  • return 1 if x > y

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 }

and

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

return the same array in opposite orders.


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

  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.

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

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

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