你会如何以同样的方式对两个数组进行排序?
hey = %w[e c f a d b g]
hoo = [1,2,3,4,5,6,7]
hey.sort #=> [a,b,c,d,e,f,g]
hoo.same_sort #=> [4,6,2,5,1,3,7]
答案 0 :(得分:6)
试一试:
hey.zip(hoo).sort
=> [["a", 4], ["b", 6], ["c", 2], ["d", 5], ["e", 1], ["f", 3], ["g", 7]]
hey.zip(hoo).sort.transpose
=> [["a", "b", "c", "d", "e", "f", "g"], [4, 6, 2, 5, 1, 3, 7]]
答案 1 :(得分:3)
您可以使用Enumerable#sort_by和Array#values_at
进行单一排序sorted_indices = hey.each_index.sort_by { |i| hey[i] }
#=> [3, 5, 1, 4, 0, 2, 6]
hey.values_at(*sorted_indices)
#=> ["a", "b", "c", "d", "e", "f", "g"]
hoo.values_at(*sorted_indices)
#=> [4, 6, 2, 5, 1, 3, 7]