我很难理解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"]
我很难理解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
算法将假设该比较函数/块将满足方法<=>
的要求:
未能提供足够的比较函数/块将导致数组的顺序未定义.
你现在应该明白为什么了
a.sort { |x, y| x <=> y }
和
a.sort { |x, y| y <=> x }
以相反的顺序返回同一array.
为了详细说明Tate Johnson添加的内容,如果在任何类上实现比较函数<=>
,您将获得以下结果
Comparable
in your class which will automatically define for you the following methods: between?
, ==
, >=
, <
, <=
和 >
.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...).