ruby - How to remove range from an array -


i'm trying find equivalent remove_range (which not exist of course) shown below. seems there no easy way implement functionality.

a = [0,2,8,2,4,5,] b = a.remove_range(1,2) #remove items between index 1 , 2 ,inclusively #expect b == [0,2,4,5] b = a.remove_range(3,4) #expect b == [0,2,8,5] 

please test @ least above 2 cases before posting solution :)

suppose size of range m, operation should requires o(1) space , o(n-m) time complexity.

edit: see people keep posting a - a[range]. not correct, remove elements exists in a[range], not remove the element belongs range.

a - a[1..2] return [0, 4, 5]. however,we want keep 3rd element 2.

you can cool tricks enumerable module:

a = [0, 2, 8, 2, 4, 5] r = 1..2 a.reject.with_index { |v, i| r.include?(i) }  # => [0, 2, 4, 5] 

note not modify original array, returns new one. can use reject! if want modify array.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -