1

If I type c.messages.reverse.delete_at(0) nothing happens, where messages is the array. If I type c.messages.delete_at(0) it deletes the first element as it should. Why does this not work with reverse?

2 Answers 2

3

That happens because reverse returns a new array, of which you are deleting the last member. You could use reverse!, which mutates the original array.

If you want to remove the last element from an array, the best way would be to use pop.

>> arr = ["a", "b", "c"]
=> ["a", "b", "c"]
>> arr.pop
=> "c"
>> arr
=> ["a", "b"]
Sign up to request clarification or add additional context in comments.

4 Comments

I see, I will have to add the new array back to the object before saving to make it stick. Thanks!
The deleted array element could be at any position however, so I can't use pop. However it feels wrong to type: messages = c.messages.reverse messages.delete_at(params[:position].to_i) c.messages = messages.reverse This would invert the reverse and make it back to normal, what's the correct way of doing this?
@jotun Can you use messages.delete_at messaages.length - params[:position].to_i ?
I just had to add in -1 like this: messages.length - 1 - params[:position].to_i to make it count properly.
2

delete_at can handle a negative index, counting backward from the end of the array (-1 is the last element):

ar = [1,2,3,4,5]
ar.delete_at(-2)
p ar #=> [1, 2, 3, 5]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.