首页 > 解决方案 > 如何连接给定文件中的两行?

问题描述

我想将一行与文本文件给出的另一行连接起来。我怎么做?

我尝试过使用带有索引的数组,但是当我这样做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]

标签: ruby

解决方案


虽然我不明白你为什么以及你想要实现这一点,但我可以弄清楚基本上你正在寻找读取/调用这些行作为索引。

请参考这个

=> file = IO.readlines('filename') # => ["line 1\n", "line 2\n", "line 3\n"]
=> file[2] # => "line 3\n"

推荐阅读