Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: slicing out n elements from an array centered around some index

Tags:

ruby

Here's an array, an index, and a number n representing how many items I want to slice out

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
index = 5
n = 3

The above arguments translates to give me 3 elements centered around index 5, which would be [4,5,6]

If the number is even, then just make an arbitrary choice of having the extra element on the left or right side. Eg: Given n = 2, [4, 5] and [5,6] are both equally valid.

But then we have to consider boundary cases. Supposing index = 1 and n = 5, it should return [0,1,2,3,4], because we've hit the boundary on the left side.

Similarly, Supposing index = 8 and n = 5, it should return [5,6,7,8,9] since we hit the boundary on the right side.

What's a nice way to write this?

like image 745
MxLDevs Avatar asked Aug 31 '25 04:08

MxLDevs


1 Answers

You can get a slice by using Array#[]

Therefore, something like the following should work fine:

arr[offset - (count / 2), count]

Provided offset and count are Fixnums, ruby will handle the division and rounding correctly to meet the requirements you gave.

EDIT | You should probably sanitize the arithmetic too, since negative offsets have a special meaning to #slice. Then you also want to sanitize the end value to allow the entire count to fit:

arr[
  [[offset - (count / 2), 0].max, arr.size - count].min,
  count
]

Getting a bit hairy now, but that's it anyway.

like image 102
d11wtq Avatar answered Sep 02 '25 19:09

d11wtq