I have a huge string being prepared by using << operator in a loop. At the end I want to delete the last 2 chars.
some_loop
str << something
end
str = str[0..-3]
I think the last operation above would consume memory and time as well, but I’m not sure. I just wanted to see if there is an operation with the opposite effect of << so I can delete those 2 last chars from the same string.
In fact, string slicing is already a fast and memory efficient operation as the string content isn’t copied until it’s really necessary.
See the detailed explanation at “Seeing double: how Ruby shares string values“.
Note that this is a somewhat classical optimization for string operations; You have it in java too and we often used similar tricks in C.
So, don’t hesitate to do:
That’s the correct, recommended and efficient way, provided you really have to remove those chars, see Sergio’s answer.