Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby/rails array all elements between two indices

I have an array like this: [7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6]

What's the simplest way to return each item in the array from position 6 until 0 where the resulting array looks like: [1,2,3,4,5,6,7]

This positions in the array can be dynamic, for example passing in 4 and 9 should return [11,12,1,2,3,4]

I'm wondering if there's a method that accomplishes this in Rails api.

Thanks in advance

EDIT Let's assume that no negative numbers, so doing array[2..-2] wont work.

Array#splice almost works for this, but if the second position is less than the first, it returns nil.

like image 307
splitter_in_the_sun Avatar asked Jun 19 '15 05:06

splitter_in_the_sun


1 Answers

def foo a, min, max
  a.rotate(min).first((max - min) % a.length + 1)
end

a = [7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6]
foo(a, 6, 0) # => [1, 2, 3, 4, 5, 6, 7]
foo(a, 4, 9) # => [11, 12, 1, 2, 3, 4]
like image 139
sawa Avatar answered Sep 25 '22 08:09

sawa