Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby File.open not creating file

I'm trying to create and write to a new file using

@logFile = File.open("C:\Users\---\Desktop\mylog.log", "w+")

And nothing happens. My program uses

  @logFile.write ("Hello")
  @logFile.flush

And this line seems to be running ok (no crashes or anything) But i can't see any newly created file.

What am i missing out here?

like image 537
Itzik984 Avatar asked Mar 26 '26 12:03

Itzik984


1 Answers

  1. Your backslashes are escaped, in a string enclosed with double quotes you need to double them, or just use the Unix notation. So "C:\\Users\\---\\Desktop\\mylog.log"

or "C:/Users/---/Desktop/mylog.log"

or 'C:\Users\---\Desktop\mylog.log'

  1. Paths in Ruby are safest in Unix notation, so even when you use backslashes for ease of copying you are better to convert them to Unix formatting.

like this 'C:\Users\---\Desktop\mylog.log'.gsub('\\','/')

The double backslash is also needed here, the ' and \ need to be escaped using single quotes.

Another tip not relevant tot the question but very handy: use the block method to open a file so that it is clear when the file is closed, see this example

File.open(path, 'w') do |file|
  file.puts "Hello"
end

The file is closed after the end.

For logging though, take a look at logger, once you used it you won't stop using it.

like image 156
peter Avatar answered Mar 29 '26 03:03

peter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!