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.



I think you need to escape the backslashes:


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"



Thanks SouravGoswami!

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

Have a great day.

1 Like

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs