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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With