我有一个值数组,一个数组决定顺序.
怎样才能按照给定的顺序重新排列阵列?
data = ['0','1','2','3','4','5'] order = [3,1,2,4,5]
我想要:
data = ['3','0','5']
解决方法
data = ["0","1","2","3","4","5"] order = [3,5] > order.map{|x| data[x]} => ["3","0","5"]
如果您不确定索引是否正确,您可以这样做:
> order.map{|x| data.fetch(x)} # will raise an exception if index out of bounds => ["3","5"]