Ruby 前 n 个元素的自定义排序

Ruby custom sorting of first n elements

我想根据我的自定义顺序对字符串数组进行排序。问题是我不知道数组中的所有元素,但我确定它有 3 个字符串 (high/med/low)。所以我希望这 3 个成为前 3 个值。终于休息了

Eg:

Incoming arrays

array1 = ["high", "not impt" , "med" , "kind of impt" , "low" ]
array2 = ["low", "rand priority", "med", "high"]

只有高中低是固定的,其余的都在不断变化或者可能根本不存在

required output ["high", "med", "low", rest.(order doesn't matter)]]

我知道我可以删除和合并,但是代码会混淆我为什么要删除和合并。还有更好的办法吗?

您可以使用 sort_by 方法并实现如下内容:

["high", "not impt" , "med" , "kind of impt" , "low" ].sort_by do |a|
  ["high", "med", "low"].index(a) || Float::INFINITY
end

index 方法 returns 012 对于 "high""med""low" 相应地和 nil 其他值。因此,"high""med""low" 将位于开头,而其他值位于结尾,因为每个值都小于 Float::INFINITY