SirCheckmatesalot
SirCheckmatesalot

Reputation: 199

How do I concatenate a string in a while loop?

I want to read some lines in a loop and concatenate them:

d = ""
while s = gets do
  d = d.concat(s)
end
puts d

After I cancel the loop with CNTRL+Z (on Windows), the output is just the last string that I read in my loop. I tried it also with + and << but with same result.

Upvotes: 0

Views: 1686

Answers (2)

Lucas
Lucas

Reputation: 2627

You can do it in two ways this way:

d = ""
while s = gets do
  d << s
end
puts d

Edit: Marc-André Lafortune noticed using += is not very good idea, so I leave only << method here.

Upvotes: 5

Marc-Andr&#233; Lafortune
Marc-Andr&#233; Lafortune

Reputation: 79562

Two good ways are to either use << or join:

d = ""
while s = gets do
  d << s
end
puts d

Or

a = []
while s = gets do
  a << s
end
puts a.join

What you don't want to do is use += in the first example. Imagine your loop iterates 200 times and returns a 100 character-long s. You will build 200 strings, of lengths 100, 200, 300, ..., 199900, 200000. That will be O(n^2).

Upvotes: 1

Related Questions