Reputation: 10350
Here is a string str
:
str = "line1
line2
line3"
We would like to add string "\n" to the end of each line:
str = "line1 \n
line2 \n
line3 \n"
A method is defined:
def mod_line(str)
s = ""
str.each_line do |l|
s += l + '\\n'
end
end
The problem is that '\n' is a line feed and was not added to the end of the str
even with escape \
. What's the right way to add '\n' literally to each line?
Upvotes: 1
Views: 1561
Reputation: 121000
The platform-independent solution:
str.gsub(/\R/) { " \\n#{$~}" }
It will search for line-feeds/carriage-returns and replace them with themselves, prepended by \n
.
Upvotes: 3
Reputation: 4927
String#gsub
/String#gsub!
plus a very simple regular expression can be used to achieve that:
str = "line1
line2
line3"
str.gsub!(/$/, ' \n')
puts str
Output:
line1 \n
line2 \n
line3 \n
Upvotes: 3
Reputation: 1319
This is the closest I got to it.
def mod_line(str)
s = ""
str.each_line do |l|
s += l
end
p s
end
Using p instead of puts leaves the \n on the end of each line.
Upvotes: 1
Reputation: 168101
\n
needs to be interpreted as a special character. You need to put it in double quotes.
"\n"
Your attempt:
'\\n'
only escapes the backslash, which is actually redundant. With or without escaping on the backslash, it gives you a backslash followed by the letter n
.
Also, your method mod_line
returns the result of str.each_line
, which is the original string str
. You need to return the modified string s
:
def mod_line(str)
...
s
end
And by the way, be aware that each line of the original string already has "\n"
at the end of each line, so you are adding the second "\n"
to each line (making it two lines).
Upvotes: 1