Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

opposite of << in ruby

Tags:

string

ruby

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.

like image 453
Amol Pujari Avatar asked Aug 20 '12 09:08

Amol Pujari


People also ask

What does =~ mean in Ruby?

=~ 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.

What is exclude in Ruby?

The exclude_end?() is an inbuilt method in Ruby returns boolean value true if the range excludes its end value, else it returns false.

How do you write not equal to in Ruby?

!= - The "not equal to" operator.


2 Answers

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.

like image 106
Denys Séguret Avatar answered Sep 23 '22 11:09

Denys Séguret


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'
like image 35
Sergio Tulentsev Avatar answered Sep 25 '22 11:09

Sergio Tulentsev