Sending an output to a file / writing to a file. Super beginner

Hello all,
First question as I start to learn programming!

I have created a script which outputs information on screen. I want to output this same information to a file; either a text file or csv file. I tried the following simple code which I found online (and nothing else):
File.write("C:\Users\ME\Documents\test\log.txt", "testing") and I tried adding the log.txt in that location thinking it would populate it with the word ‘testing’. It didn’t and I got the error message (which I think I have attached).

Is my approach completely wrong? I am running Ruby through another application (i.e. the application has a ruby interface which allows me to select and run .rb scripts).

Many thanks for reading.

Jool

image

I think you need to escape the backslashes:

"C:\\Users\\ME\\Documents\\test\\log.txt"

Or you can use single quotes to wrap the string:

File.write('C:\Users\ME\Documents\test\log.txt', "testing")

The later escapes the \ automatically so you don’t have to think about that.

If you ever need to concatenate a user’s given filename:

file = 'log'
puts 'C:\Users\ME\Documents\test\\' "#{file}.txt"

Outputs:

C:\Users\ME\Documents\test\log.txt

Thanks SouravGoswami!

That worked. Thanks so much - you’ve made my Tuesday!

Have a great day.

1 Like