user7055375
user7055375

Reputation:

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.

Upvotes: 1

Views: 255

Answers (6)

Eric Duminil
Eric Duminil

Reputation: 54303

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.

Upvotes: 5

TPReal
TPReal

Reputation: 1585

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

a=a.drop_while.with_index{|e,i| e==i}

Upvotes: 3

Oleksandr Holubenko
Oleksandr Holubenko

Reputation: 4440

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]

Upvotes: 0

Douglas Tyler Gordon
Douglas Tyler Gordon

Reputation: 569

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

Upvotes: 2

Ginty
Ginty

Reputation: 3501

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.

Upvotes: 2

Kris
Kris

Reputation: 19958

In short form:

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

In longer form:

if a.first == 0
  a[3..(a.size)]
else
  a
end

Upvotes: -1

Related Questions