Ruby,基于另一个数组重新排序数组?

时间:2014-08-19 23:37:54

标签: ruby

我想根据ary中指定的索引订购order

# Ruby
ary = ['a', 'b', 'c', 'd']
order = [2, 3, 0, 1]

# Result I want
ary = ['c', 'd', 'a', 'b']

3 个答案:

答案 0 :(得分:11)

ary = ['a', 'b', 'c', 'd']
order = [2, 3, 0, 1]

ary.values_at(*order)
  #=> ["c", "d", "a", "b"]

答案 1 :(得分:0)

你可以这样做:

ary = ['a', 'b', 'c', 'd']
order = [2, 3, 0, 1]
sorted_array = []

order.each do |i|
  sorted_array.push(ary[i])
end

虽然看着它,但卡里的回答更好。

答案 2 :(得分:0)

ary = ['a', 'b', 'c', 'd']
order = [2, 3, 0, 1]

new_array = []

order.each do |index| #This returns the array you want.
    new_array << ary[index]
end