5

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.

Joe Kennedy
  • 9,365
  • 7
  • 41
  • 55
Amol Pujari
  • 2,280
  • 20
  • 42

3 Answers3

8

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.

Community
  • 1
  • 1
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • +1 for the link pasted above -> http://patshaughnessy.net/2012/1/18/seeing-double-how-ruby-shares-string-values – Amol Pujari Aug 20 '12 at 10:10
3

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'
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
  • yes, joining some array elements with `, `. But, I know I should be doing some bench-marking on my own, but still want to hear quick comments about how bad it might be to call join when the data strings are too many and huge – Amol Pujari Aug 20 '12 at 09:37
  • Then this answer is for you :) – Sergio Tulentsev Aug 20 '12 at 09:37
1

If the last two characters are linefeed/newline (CR/LF) you may use String.chomp (or String#chomp! if you want to modify the string).

Else you may use:

2.times{ string.chop! }

or

string.chop!
string.chop!
knut
  • 27,320
  • 6
  • 84
  • 112
  • Why do tell about `chomp` in the text and give examples using `chop`? – sawa Aug 20 '12 at 12:10
  • 1
    `chomp` is for CR/LF. The example with `chop` is in the 'else'-section (it removes the last character). – knut Aug 20 '12 at 19:07