Reputation: 23
I am new in ruby programming. I am trying to read a textfile line by line.
Here is my sample textfile:
john
doe
john_d
somepassword
Here is my code:
f = File.open('input.txt', 'r')
a = f.readlines
n = a[0]
s = a[1]
u = a[2]
p = a[3]
str = "<user><name=\"#{n}\" surname=\"#{s}\" username=\"#{u}\" password=\"#{p}\"/></user>"
File.open('result.txt', 'w') { |file| file.print(str) }
The output should look like this:
<user><name="john" surname="doe" username="john_d" password="somepassword"/></user>
But the result.txt looks like this. It includes newline character for every line:
<user><name="john
" surname="doe
" username="john_d
" password="somepassword"/></user>
How can i correct this?
Upvotes: 2
Views: 187
Reputation: 110665
FName = 'temp'
File.write FName, "john
doe
john_d
somepassword"
#=> 28
Here are two ways.
s = "<user><name=\"%s\" surname=\"%s\" username=\"%s\" password=\"%s\"/></user>"
puts s % File.readlines(FName).map(&:chomp)
# <user><name="john" surname="doe" username="john_d" password="somepassword"/></user>
puts s % File.read(FName).split("\n")
# <user><name="john" surname="doe" username="john_d" password="somepassword"/></user>
See String#% and, as mentioned in that doc, Kernel#sprintf.
Upvotes: 0
Reputation: 13
As @iGian already mentioned, chomp
is a good option to clean up your text. I am not sure which version of Ruby you are using, but here is the link to the official Ruby version 2.5 documentation on chomp
just so you see how it is going to help you: https://ruby-doc.org/core-2.5.0/String.html#method-i-chomp
See the content of variable a
after using chomp
:
2.4.1 :001 > f = File.open('input.txt', 'r')
=> #<File:input.txt>
2.4.1 :002 > a = f.readlines.map! {|line| line.chomp}
=> ["john", "doe", "john_d", "somepassword"]
Depending on how many other corner cases you expect to see from your input string, here is also another suggestion that can help you to clean up your strings: strip
with link to its official documentation with examples: https://ruby-doc.org/core-2.5.0/String.html#method-i-strip
See the content of variable a
after using strip
:
2.4.1 :001 > f = File.open('input.txt', 'r')
=> #<File:input.txt>
2.4.1 :002 > a = f.readlines.map! {|line| line.strip}
=> ["john", "doe", "john_d", "somepassword"]
Upvotes: 1
Reputation: 11183
As explained by spickermann, also just change line two into:
a = f.readlines.map! { |line| line.chomp }
Upvotes: 1
Reputation: 106792
It includes newline character for every line, because there is a newline character at the end of every line.
Just removed it when you don't need it:
n = a[0].gsub("\n", '')
s = a[1].gsub("\n", '')
# ...
Upvotes: 3