Erran Morad
Erran Morad

Reputation: 4743

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 ?

Upvotes: 0

Views: 48

Answers (2)

prashant
prashant

Reputation: 108

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]]

Upvotes: 1

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369458

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.

Upvotes: 4

Related Questions