Natalia Natalia - 1 year ago 35
Ruby Question

How do I remove the beginning elements of my array only if the first element satisfies a condition?

In Ruby, let's say I have an array of ordreed, unique numbers

[0, 1, 2, 4, 6, 8, 10]


If the first element of the array is zero, how do I remove all the elements from teh beginning of the array that are consecutive, starting wiht zero? That is, in the above example, I would want to remove "0", "1", and "2" leaving me with

[4, 6, 8, 10]


But if my array is

[1, 2, 3, 10, 15]


I would expect the array to be unchanged because the first element is not zero.

Answer Source

Sounds like you're trying to delete entities if they match their idx (provided the first idx is 0). Try this:

   if array.first == 0 
      new_array = array.reject.each_with_index{ |item, idx| item == idx } 
  end

Although this will only work with ordered arrays of unique numbers, if you're not sure that they are then include: array = array.sort.uniq

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download