首先对数组的特定项进行排序

时间:2010-05-12 18:40:41

标签: ruby-on-rails ruby arrays sorting

我有一个看起来像这样的ruby数组:

my_array = ['mushroom', 'beef', 'fish', 'chicken', 'tofu', 'lamb']

我想对数组进行排序,以便'chicken'和'beef'是前两项,然后其余项按字母顺序排序。我该怎么做呢?

4 个答案:

答案 0 :(得分:11)

irb> my_array.sort_by { |e| [ e == 'chicken' ? 0 : e == 'beef' ? 1 : 2, e ] }
 #=> ["chicken", "beef", "fish", "lamb", "mushroom", "tofu"]

这将为数组的每个元素创建一个排序键,然后按排序键对数组元素进行排序。由于排序键是一个数组,因此它按位置进行比较,因此[0, 'chicken'] < [1, 'beef'] < [2, 'apple' ] < [2, 'banana']

如果您不知道在运行之前要将哪些元素排序到前面,您仍然可以使用此技巧:

 irb> promotables = [ 'chicken', 'beef' ]
  #=> [ 'chicken', 'beef' ]
 irb> my_array.sort_by { |e| [ promotables.index(e) || promotables.size, e ] }
  #=> ["chicken", "beef", "fish", "lamb", "mushroom", "tofu"]
 irb> promotables = [ 'tofu', 'mushroom' ]
  #=> [ 'tofu', 'mushroom' ]
 irb> my_array.sort_by { |e| [ promotables.index(e) || promotables.size, e ] }
  #=> [ "tofu", "mushroom", "beef", "chicken", "fish", "lamb"]

答案 1 :(得分:6)

如果只在运行时获取数据,那么我的通用性更高,更有用。

my_array = ['mushroom', 'beef', 'fish', 'chicken', 'tofu', 'lamb']
starters = ['chicken', 'beef']
starters + (my_array.sort - starters)
# => ["chicken", "beef" "fish", "lamb", "mushroom", "tofu"]

答案 2 :(得分:1)

另一种解决方法:

array = [1,2,2,3,3,4,5]
array.select {|element| element == 2} + array.select {|element| element != 2}
# => [2, 2, 1, 3, 3, 4, 5]

答案 3 :(得分:1)

可以做到

firsts = ["chicken", "beef"]
[*firsts, *(my_array.sort - firsts)]

#=> ["chicken", "beef", "fish", "lamb", "mushroom", "tofu"]