Reputation: 199
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
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
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