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.
=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter.
The exclude_end?() is an inbuilt method in Ruby returns boolean value true if the range excludes its end value, else it returns false.
!= - The "not equal to" operator.
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:
str = str[0..-3]
That's the correct, recommended and efficient way, provided you really have to remove those chars, see Sergio's answer.
Are you, by any chance, joining some array elements with a separator? Something like this?
names = ['Mary', 'John', 'Dave']
res = ''
names.each do |n|
res << n << ', '
end
res # => 'Mary, John, Dave, '
If yes, then there's easier path.
names.join(', ') # => 'Mary, John, Dave'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With