Erase the last value in an array

4

I have an array in which each index consists of a letter, which together form a sentence. I was not able to delete the last value of the array in any way. After researching a lot, I managed to delete it, but I'm thinking that the code is very "plug hole". Look how I tried the first time:

p "Primeiro teste:"
array = ["t", "e", "s", "t", "e", "_", "t", "e", "s", "t", "e"]

array.delete(array.last)

Obviously it will delete all the "and" from the array. So, here are my attempts:

p "Segundo teste:"
array = ["t", "e", "s", "t", "e", "_", "t", "e", "s", "t", "e"]

// Retorna o index último item do último elemento do array
array.delete_at(array.rindex(array.last))

The other:

p "Terceiro teste:"
array = ["t", "e", "s", "t", "e", "_", "t", "e", "s", "t", "e"]

// Inverte o array, deleta o primeiro elemento e inverte novamente
array.reverse!.shift.reverse!

All running codes: link

Some more efficient and clean way to get the job done? I did not find a specific function.

    
asked by anonymous 25.04.2015 / 02:50

1 answer

4

You can also use the pop()

array = ["t", "e", "s", "t", "e", "_", "t", "e", "s", "t", "e"]
p array

array.pop()
p "Deletando"
p array

# ["t", "e", "s", "t", "e", "_", "t", "e", "s", "t", "e"]
# "Deletando:"
# ["t", "e", "s", "t", "e", "_", "t", "e", "s", "t"]

See DEMO

    
25.04.2015 / 03:02