ruby - 如何连接给定文件中的两行?
问题描述
我想将一行与文本文件给出的另一行连接起来。我怎么做?
我尝试过使用带有索引的数组,但是当我这样做line + line[index + 1]
时,它不会将前一行与第二行连接起来。
def createWordList(filename)
wordArray = Array.new
for i in 1..6
i = gets.chomp
i.delete("\n\r\t")
wordArray.push(i)
end
file = File.open(filename, "r+")
wordArray.each_with_index do |item, index|
file.puts(item)
item += item[index + 1]
file.puts(item)
end
end
createWordList("words.txt")
Ì 期待line[index + 1]
返回下一行,但它反而返回了字母line[index + 1]
解决方案
虽然我不明白你为什么以及你想要实现这一点,但我可以弄清楚基本上你正在寻找读取/调用这些行作为索引。
请参考这个。
=> file = IO.readlines('filename') # => ["line 1\n", "line 2\n", "line 3\n"]
=> file[2] # => "line 3\n"
推荐阅读
- python - 如何使 PyQt5 QTreeview 节点在代码中可编辑?
- javascript - 使用 React Navigation,如何强制抽屉导航器弹出到堆栈顶部?
- c# - C#:如何转换父级,但只有父级而不是子级
- python-3.x - 如何分析没有真实标签的聚类的完整性?
- typescript - 从基类返回子类的新实例:循环引用
- sql - postgresql 的 ON CONFLICT DO UPDATE 是否会产生大量死元组?
- c - LuaJIT 能比 C 快吗?
- bash - Bash:-d 的使用给出了错误的结果
- javascript - 用于响铃的 Vscode 键盘快捷键
- javascript - Onclick 事件将元素向下移动特定数量的像素