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
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"]
4 Comments
jotun
I see, I will have to add the new array back to the object before saving to make it stick. Thanks!
jotun
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?
alex
@jotun Can you use
messages.delete_at messaages.length - params[:position].to_i ?jotun
I just had to add in -1 like this: messages.length - 1 - params[:position].to_i to make it count properly.