Delete the last value in an array

Asked

Viewed 610 times

4

I have an array in which each index contains a letter, which together form a sentence. I was unable to delete the last array value. After searching a lot, I was able to delete, but I think the code is too "cover 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 "and" of 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 the codes running: http://repl.it/knV

Any more efficient and clean way to do the job? I couldn’t find a specific function.

1 answer

4


You can also use the method 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

  • 1

    Perfect! I have a slight impression that I had tested this command before, but at the time I don’t know why it didn’t work. Thank you :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.