首页 > 解决方案 > How can i read lines in a textfile with RUBY

问题描述

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?

标签: ruby

解决方案


它包括每一行的换行符,因为每一行的末尾都有一个换行符。

不需要时将其删除:

n = a[0].gsub("\n", '')
s = a[1].gsub("\n", '')
# ...

推荐阅读