简体   繁体   中英

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

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#[] :

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.

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 -

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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