1

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.

6 Answers6

5

You could use a mix of drop_while and with_index to only remove the first matching elements:

[0, 1, 2, 4, 6, 8, 10].drop_while.with_index{|x, i| x == i}
# [4, 6, 8, 10]

[1, 1, 2, 4, 6, 8, 10].drop_while.with_index{|x, i| x == i}
# [1, 1, 2, 4, 6, 8, 10]

Note that the second and third elements don't get deleted in the second example, even though they're equal to their indices.

Eric Duminil
  • 52,989
  • 9
  • 71
  • 124
3

Drop elements, as long as they are equal to their index:

a=a.drop_while.with_index{|e,i| e==i}
TPReal
  • 1,539
  • 12
  • 26
2

You could do:

x = -1
while my_array.first == x + 1 do
  x = my_array.shift
end

Note that array.shift is the same as array.pop except that it works from the start of the array.

Ginty
  • 3,483
  • 20
  • 24
2

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

  • True, but that isn't an ordered array which OP specified it would be. Also, in my edit I indicated that you can fix any array with `array.sort.uniq` – Douglas Tyler Gordon May 22 '17 at 19:19
0

If I understand you right, then it can be one of possible solutions:

def foo(array)
  if array.first.zero?
    array.keep_if.with_index { |e, ind| e != ind }
  else
    array
  end
end

> foo([0, 1, 2, 5, 6, 7])
#=> => [5, 6, 7]
> foo([1, 2, 3])
#=> [1, 2, 3]
Oleksandr Holubenko
  • 4,310
  • 2
  • 14
  • 28
-1

In short form:

a[0] == 0 ? a[3..-1] : a

In longer form:

if a.first == 0
  a[3..(a.size)]
else
  a
end
Kris
  • 19,188
  • 9
  • 91
  • 111