ruby - 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?
解决方案
它包括每一行的换行符,因为每一行的末尾都有一个换行符。
不需要时将其删除:
n = a[0].gsub("\n", '')
s = a[1].gsub("\n", '')
# ...
推荐阅读
- c# - 从 StandardOutput.ReadToEnd 获取整个输出时遇到问题
- python-3.x - 使用 PySpark 在读取时过滤镶木地板文件
- react-native - React native 在异步函数上不显示错误
- python - 使用 struct 和 char* 从 python 取回数据的 Ctypes
- mysql - 在 SELECT 子句中使用 INNER JOIN 返回不正确的值
- r - 使用 R 中的正则表达式从网页中提取文本和数字
- magento - 在 HEAD 中覆盖 CSS 和 JS 文件的类型属性
- continuous-integration - CD 中的自动化测试
- r - 从数据框中选择列进行线性回归 r
- javascript - WordPress 更新后 JS 不再工作 - Uncaught TypeError: $ is not a function