繁体   English   中英

在Ruby中将数组转换为范围数组

[英]Converting a array to an array of ranges in Ruby

我有一个数字数组。 我想将其转换为范围数组。 例:

input = [0,10,20,30]

output = [0..10, 10..20, 20..30, 30..Infinity] 

在Ruby中有直接的方法吗?

是的,可能:

input = [0,10,20,30]
(input + [Float::INFINITY]).each_cons(2).map { |a,b| a..b }
 # => [0..10, 10..20, 20..30, 30..Infinity] 

单程:

output = input.zip(input[1..-1] << 1.0/0).map { |r| Range.new(*r) }

说明

input = [0,10,20,30]

a = input[1..-1]
  #=> [10, 20, 30]

b = a << 1.0/0
  #=> [10, 20, 30, Infinity]

c = input.zip(b)
  #=> [[0, 10], [10, 20], [20, 30], [30, Infinity]]

output = c.map { |r| Range.new(*r) }
  #=> [0..10, 10..20, 20..30, 30..Infinity]

可能的选择

如果您想要一个数组数组,则只需更改该块:

output = input.zip(input[1..-1] << 1.0/0).map { |f,l| [f..l] }
  #=> [[0..10], [10..20], [20..30], [30..Infinity]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM