How do you write a newline to a file in Ruby?
My code to write to the file is:
[Full code request]
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) }
But the problem is that that line ^ is in a loop. Meaning it's repeated over and over again quite a lot of times actually. So whenever you open the output file, the output is squashed together. So what the program I've wrote basically does is it scrambles words into as many ways as possible. So if my input was "Abcdefgh", then the output in the file is going to be displayed as one continuous line:
bdfcegAhhbgfeAcdhcedbAgfdfcAhgebefcdbghAdAfhegbcAegdfhbcbchdgefAhAbedfcgdAfcbhgefhgdAbceefdhcgAbAefbhgcdfAcebdhgAebgchfddhcfAbegcAdfbhgecAgdfhebedAghbfcedbAchgfbhAcgfdeceghAbfddAbfehcgbAhefdgcecfghbdAAhcgdfbedchAgfbebfhAgecdedAhcbgfAfdceghbehdcAbfgcegdhbfAfdAbchgegAhbfecdgeAdhfcbcbdAehfgfhgbcAedchdgbefAfhecdAbgAbedgcfhehcgfbdAAhgcebfdbAcehgfddfchgebAhcAbegdffAbehgcdchdbgAfebeAhgdfcbegcdhfAfecbdhAgdbfehgAcdbcehgfAgdehfcbAbgedAcfhdgcAfehbdfhAgecbcAgdhebfghbAefcdgebhAfdcgecdbAfhgbcAhfedhAbfgdcebAedfhcgbdfchAge
So, what I want to do is I want to have some sort of separation between the output. So every time it's outputted there is either a new line, a space, a pipe, a slash, etc.
I've already tried
File.open("output.txt","a+") {|f| f.write(x)+" " }
and
File.open("output.txt","a+") {|f| f.write(x)," " }
and
File.open("output.txt","a+") {|f| f.write(x)" " }
but it doesn't work. So how might I be able to solve this?
File.open("output.txt","a+") { |f| f.puts(x) }
should do it
Edit:
You could append a newline to x like this:
x + "\n"
Edit 2:
You want open the file outside of the loop. Try this:
File.open('testfile.txt', 'a+') do |f|
(1..3).each do |i|
f.puts("test #{i}")
end
end
It works on my machine(MBP). It puts 3 lines in the file:
test 1
test 2
test 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With