简体   繁体   English

如何将一个数组切成不同大小的数组并将它们组合在一起?

[英]How do I slice an array into arrays of different sizes and combine them?

I want something as simple as the pseudocode below: 我想要像下面的伪代码一样简单的东西:

ar = [4,5,6,7,8,9]
last = ar.length-1
s = ar[0, 1..3, last] #fake code
puts s

Expected output has no 8: 4,5,6,7,9 预期输出没有8:4、5、6、7、9

Error: 错误:

bs/test.rb:12:in `[]': wrong number of arguments (3 for 2) (ArgumentError)

I know that it can accept only two args. 我知道它只能接受两个参数。 Is there a simple way to get what I need ? 有什么简单的方法可以得到我需要的东西吗?

You almost have it, you're just using the wrong method, you should be using Array#values_at instead of Array#[] : 差不多了,只是使用了错误的方法,应该使用Array#values_at而不是Array#[]

ar.values_at(0, 1..3, -1)
# => [4, 5, 6, 7, 9]

Also note that in Ruby, indices "wrap around", so that -1 is always the last element, -2 is second-to-last and so on. 还要注意,在Ruby中,索引“环绕”,因此-1始终是最后一个元素, -2是倒数第二个,依此类推。

You can do it this way also - 您也可以通过这种方式-

ar = [4,5,6,7,8,9]
arr = []
arr << ar[0..0]   #arr[0] will return a single value but ar[0..0] will return it in array.
arr << ar[1..3]
arr << ar[-1..-1]

on printing arr it will give following output - 在打印arr ,它将给出以下输出-

[[4], [5, 6, 7], [9]]

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

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