部分排序在Ruby中的数组 [英] Partially sorting an array in Ruby

查看:93
本文介绍了部分排序在Ruby中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按字母顺序在其他一词,这是我想在数组的末尾成员的排斥排序数组的数组。假设数组如下所示:

 城市= [[悉尼],[其他] [墨尔本]]

简单地说, cities.sort 只是做到以下几点:

  [墨尔本号],[其他] [悉尼]]

我想成员与被按字母顺序排列 [其他] 结尾,像这样:

  [墨尔本号],[悉尼],[其他]

有人点我在这里正确的方向?


解决方案

  cities.sort_by做|(市)|
  [城市==其他? 1:0,城市]
结束
#=> [墨尔本号],[悉尼],[其他]

有几件事情怎么回事。首先是所谓一个解构绑定 |(市)| 。 阵列城市的每一个元素本身是一个数组,我们感兴趣的是该数组的第一个元素。这就是围绕括号(市)让我们。

接下来是sort_by返回一个数组。当两个阵列进行比较时,两个阵列的第一元件进行比较。如果它们相等,则第二元素进行比较,依此类推。正因为如此,我们可以使用数组的第一个元素为主要排序顺序:

 城市==其他? 1:0

和阵列作为二级排序的第二个元素:

 城市

主要排序顺序的原因其他在排序结束时放。否则,元素由城市来排序。

I'm trying to sort an array of arrays alphabetically at the exclusion of the word "Other", which is a member that I want at the end of the array. Let's say that the array looks like the following:

cities = [["Sidney"], ["Other"], ["Melbourne"]]

Simply saying, cities.sort just do the following:

[["Melbourne"], ["Other"], ["Sidney"]]

I would like the members to be alphabetically ordered with ["Other"] at the end, like so:

[["Melbourne"], ["Sidney"], ["Other"]]

Can someone point me in the right direction here?

解决方案

cities.sort_by do |(city)|
  [city == 'Other' ? 1 : 0,  city]
end
# => [["Melbourne"], ["Sidney"], ["Other"]]

There are a few things going on here. First is what's called a destructuring bind: |(city)|. Each element of the cities array is itself an array, and we're interested in the first element of that array. That's what the parentheses around (city) get us.

Next is that sort_by returns an array. When two arrays are compared, the first elements of the two arrays are compared. If they are equal, then the second elements are compared, and so on. Because of this, we can use the first element of the array as the primary sort order:

city == 'Other' ? 1 : 0

and the second element of the array as the secondary sort order:

city

The primary sort order causes 'Other' to be put at the end of the sort. Otherwise, the elements are sorted by city.

这篇关于部分排序在Ruby中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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