ruby/rails array all elements between two indices -
i have array this: [7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6]
what's simplest way return each item in array position 6 until 0 resulting array looks like: [1,2,3,4,5,6,7]
this positions in array can dynamic, example passing in 4 , 9 should return [11,12,1,2,3,4]
i'm wondering if there's method accomplishes in rails api.
thanks in advance
edit let's assume no negative numbers, doing array[2..-2] wont work.
array#splice works this, if second position less first, returns nil.
class array def get_sub_array(start,last) (start > last) ? (self[start..-1] + self[0..last]) : self[start..last] end end then
a = [7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6] a.get_sub_array(6,0) #[1, 2, 3, 4, 5, 6, 7] or if don't want monkey patch
you have method
def get_sub_array(array, start,last) (start > last) ? (array[start..-1] + array[0..last]) : array[start..last] end = [7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6] get_sub_array(a,6,0) #[1, 2, 3, 4, 5, 6, 7]
Comments
Post a Comment