整数数组到范围数组 [英] Array of integers into array of ranges

查看:64
本文介绍了整数数组到范围数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何将整数数组更改为范围数组.例如,我要使用此数组:

I'm trying to figure out how I can change array of integers into array of ranges. For example I want to take this array:

ar = [0, 49, 14, 30, 40, 23, 59, 101]

进入

ar = [0..49, 14..30, 40..23, 59..101]

给定数组始终将是偶数.我想将每两个值作为范围的边界.

Given array always will be even. I want to take each two values as borders of ranges.

我试图将其分为两个数组.一个带有奇数索引,第二个带有偶数索引.

I have tried to seperate it for two arrays. One with odd indexes second with even.

a = ar.select.with_index{|_,i| (i+1) % 2 == 1}
b = ar.select.with_index{|_,i| (i+1) % 2 == 0}

我不知道如何使用它们来创建范围,我也想避免创建诸如 a b 之类的冗余变量.我不想对任何值进行排序.范围 40..23 是有意的.

I don't have an idea how to use them to create ranges, also I would like to avoid creating redundant variables like a and b. I don't want to sort any values. Range 40..23 is intentional.

推荐答案

 ar.each_slice(2).map { | a, b | a..b }

这篇关于整数数组到范围数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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