如何快速给出重新排序的顺序一个Ruby数组? [英] How do I quickly reorder a Ruby Array given an order?

查看:137
本文介绍了如何快速给出重新排序的顺序一个Ruby数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有值的阵列,且其中确定的顺序数组。

如何快速重新安排给定的顺序数组?

 数据= ['0','1','2','3','4','5']为了= [3,1,2,0,4,5]

我想:

 数据= ['3','1','2','0','4','5']


解决方案

 数据=0,1,2,3,4, 5]为了= [3,1,2,0,4,5]> order.map {| X |数据[X]}
 = GT; [3,1,2,0,4,5]

如果您不能确定,如果指数是正确的,你可以这样做:

 > order.map {| X | data.fetch(X)}#将抛出一个异常,如果索引越界
 = GT; [3,1,2,0,4,5]

I have an array of values, and an array which determines the order.

How can I quickly re-arrange the array in the given order?

data = ['0','1','2','3','4','5']

order = [3,1,2,0,4,5]

I want:

data = ['3','1','2','0','4','5']

解决方案

data =  ["0", "1", "2", "3", "4", "5"]

order = [3, 1, 2, 0, 4, 5]

> order.map{|x| data[x]}
 => ["3", "1", "2", "0", "4", "5"]

If you are not sure if the indices are correct, you can do this:

> order.map{|x| data.fetch(x)}     # will raise an exception if index out of bounds
 => ["3", "1", "2", "0", "4", "5"]

这篇关于如何快速给出重新排序的顺序一个Ruby数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆