了解`sort!`块 [英] Understanding `sort!` block

查看:56
本文介绍了了解`sort!`块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我有一个数组

letter = ['a','b','c','a','b','c','a','b','b']

有人可以解释下面的返回值吗?

Can someone kindly explain the following return value?

letter.sort! { |x| letter.count(x) }
 #=> ["b", "b", "a", "c", "c", "a", "b", "b", "a"]

推荐答案

在定义sortsort!块时,您必须接受两个参数,通常为ab.这是排序操作当时正在比较的两个元素,因此将以不同的对重复调用此块.

When you define a sort or sort! block you are obligated to take in two arguments, typically a and b. These are the two elements the sort operation is comparing at the time, so this block will be called repeatedly with various pairs.

对返回的内容有一定的限制,根据定义,您只能返回-1、0或+1 .其他值可能会起作用,但不属于规范的一部分.如果a应该在该系列中的b之后,则返回-1;如果它们等同于0,则返回1;如果b应该在a之后,则返回1.

There are constraints imposed on what you return, that by definition you should return -1, 0 or +1 only. Other values may work, but are not part of the specification. You return -1 if a should come after b in the series, 0 if they are equivalent, and 1 if b should come after a.

此外,对于任何给定的abc值集,您应该返回一致的结果,使得如果a < bb < c然后是a < c.如果返回随机值,则数组将完全混乱,并且不一定会完全排序.排序算法的优化取决于一致的结果.如果您说ac之后,那么所有在a之后的值也必须在c之后.

Additionally for any given set of a, b and c values, you should return consistent results such that if a < b and b < c then a < c. If you return random values your array will be a total mess and won't necessarily be completely sorted. Optimizations in the sort algorithm depend on consistent results. If you say a comes after c then all values that come after a must come after c as well.

Ruby非常有可能将所有正值折叠成一个迹象,表明第二个术语早于第一个术语.由于您在所有情况下都返回一个正值,因此您要告诉排序算法,所有值都在所有其他值之前,这完全是胡说八道,因为这种情况永远不会发生.

It's highly probable that Ruby is collapsing all positive values into an indication that the second term comes before the first. Since you return a positive value for all cases you're telling the sort algorithm that all values come before all other values, which is total nonsense, as that can never happen.

因此,简而言之,您会收到垃圾邮件,因为您给了sort函数垃圾邮件,并且应用了垃圾进,垃圾出原理.

So, in short, you're getting junk back because you're giving the sort function junk and the Garbage In, Garbage Out principle applies.

解决方法是使用sort_by方法,该方法仅使用一个参数并为您处理这些比较:

The way around this is to use the sort_by method which takes only one argument and handles these comparisons for you:

letters.sort_by! { |x| letter.count(x) }

这篇关于了解`sort!`块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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