如何在 Ruby 中为文件写入换行符?
我要写入文件的代码是:
[完整代码请求]
print("Word:") #Prompt for word to scrambe
word = gets.chomp #Inputs word
wordLength = word.length #Gets word length
randomAmount = wordLength * wordLength #Finds out how many ways to randomize
amountDone = 0 #Loop variable for process of randomizing
while amountDone != randomAmount
puts "---------------------------\n"
x = word.chars.to_a.shuffle #Changes each character to an array and randomizez them
File.open("output.txt","a+") {|f| f.write(x)}
puts "#{amountDone}:\n #{x}"
amountDone += 1
puts "---------------------------\n"
end
puts "Type any key to continue..."
endWord = gets.chomp #Close program prompt
-
File.open("output.txt","a+") {|f| f.write(x) }
但问题是那行 ^ 在一个循环中。这意味着它实际上一遍又一遍地重复了很多次。因此,每当您打开输出文件时,输出都会被压缩在一起。所以我写的程序基本上所做的就是将单词打乱成尽可能多的方式。因此,如果我的输入是“Abcdefgh”,那么文件中的输出将显示为一个连续的行:
bdfcegAhhbgfeAcdhcedbAgfdfcAhgebefcdbghAdAfhegbcAegdfhbcbchdgefAhAbedfcgdAfcbhgefhgdAbceefdhcgAbAefbhgcdfAcebdhgAebgchfddhcfAbegcAdfbhgecAgdfhebedAghbfcedbAchgfbhAcgfdeceghAbfddAbfehcgbAhefdgcecfghbdAAhcgdfbedchAgfbebfhAgecdedAhcbgfAfdceghbehdcAbfgcegdhbfAfdAbchgegAhbfecdgeAdhfcbcbdAehfgfhgbcAedchdgbefAfhecdAbgAbedgcfhehcgfbdAAhgcebfdbAcehgfddfchgebAhcAbegdffAbehgcdchdbgAfebeAhgdfcbegcdhfAfecbdhAgdbfehgAcdbcehgfAgdehfcbAbgedAcfhdgcAfehbdfhAgecbcAgdhebfghbAefcdgebhAfdcgecdbAfhgbcAhfedhAbfgdcebAedfhcgbdfchAge
所以,我想做的是我想在输出之间进行某种分离。所以每次输出时都会有一个新行、一个空格、一个管道、一个斜杠等。
我已经试过了
File.open("output.txt","a+") {|f| f.write(x)+" " }
和
File.open("output.txt","a+") {|f| f.write(x)," " }
和
File.open("output.txt","a+") {|f| f.write(x)" " }
但它不起作用。那么我怎么能解决这个问题呢?