2

Given an array

x = [2, 3, 4, 5, 6, 7]

I'd like to slice it in half at a certain point/index and create two subarrays of such cut, but leaving out the index. Example:

x = [2, 3, 4, 6, 70, 10]
left, right = x.slice_at_index(2)
left  = [2, 3]
right = [6, 70, 10]

I've tried with each_index, slice, chunk but can't leave out the index element.

ndnenkov
  • 35,425
  • 9
  • 72
  • 104
Leo
  • 129
  • 9

5 Answers5

3
left, right = x.take(index), x.drop(index.next)
ndnenkov
  • 35,425
  • 9
  • 72
  • 104
1
left = x[0..1]
right = x[3..-1]
user3033467
  • 1,078
  • 15
  • 24
  • He is saying " leaving out the index". The value at index should not be present at the result array. – Gopal Oct 18 '16 at 13:34
1

I think, docs like about array should help you next time.

So, UPD solution for you:

x = [2, 3, 4, 6, 70, 10]
left, right = x.shift(2), x.drop(2.pred)

> left
=> [2, 3]
> right
=> [6, 70, 10] 
Oleksandr Holubenko
  • 4,310
  • 2
  • 14
  • 28
0

You can write a method:

def slice_at_index(array, index)
  left = array[0...index]  # 3 dots vs 2
  right = array[(index + 1)..-1]
  return [left, right]
end

But, I would generally avoid multiple assignment such as left, right = slice_at_index(x, 2) as a style rule.

Stefan Lyew
  • 387
  • 2
  • 15
0

The easiest way, and I think most readable, is to use the range operator .. to specify the indexes you want out of the array.

def slice_at(array, index)
  left = array[0..(index - 1)]
  right = array[(index + 1)..-1]
  return [left, right]
end

If you'd like to learn more about how the range operator works when used this way, read this post.

Remember that you can use ... or .. in Ruby to generate ranges. Using three dots will include the starting point, but exclude the ending point, while using two dots will include both the starting and ending points. See more here.

Community
  • 1
  • 1
Matt C
  • 4,470
  • 5
  • 26
  • 44