Search code examples
rubyarraysregexdigits

Ruby Array - Delete first 10 digits


I have an array in Ruby and I would like to delete the first 10 digits in the array.

array = [1, "a", 3, "b", 2, "c", 4, "d", 5, "a", 1, "z", 7, "e", 21, "q", 30, "a", 4, "t", 7, "m", 5, 1, 2, "q", "s", "l", 13, 46, 31]

It would ideally return

['a', 'b', 'c', 'd', 'a', 'z', 'e', 'q', 0, 'a', 4, t, 7, m, 5 , 1, 2, q, s, 1, 13, 46, 31]

By removing the first 10 digits (1,3,2,4,5,1,7,2,1,3).

Note that 21(2 and 1) and 30(3 and 0) both have 2 digits

Here's what I've tried

digits = array.join().scan(/\d/).first(10).map{|s|s.to_i}
=> [1,3,2,4,5,1,7,2,1,3]
elements = array - digits

This is what I got

["a", "b", "c", "d", "a", "z", "e", 21, "q", 30, "a", "t", "m", "q", "s", "l", 13, 46, 31]

Now it looks like it took the difference instead of subtracting.

I have no idea where to go from here. and now I'm lost. Any help is appreciated.


Solution

  • To delete 10 numbers:

    10.times.each {array.delete_at(array.index(array.select{|i| i.is_a?(Integer)}.first))}
    array
    

    To delete 10 digits:

    array = [1, "a", 3, "b", 2, "c", 4, "d", 5, "a", 1, "z", 7, "e", 21, "q", 30, "a", 4, "t", 7, "m", 5, 1, 2, "q", "s", "l", 13, 46, 31]
    i = 10
    while (i > 0) do
        x = array.select{|item| item.is_a?(Integer)}.first
        if x.to_s.length > i
          y = array.index(x)
          array[y] = x.to_s[0, (i-1)].to_i
        else
          array.delete_at(array.index(x))
        end
        i -= x.to_s.length
    end
    array