Itzik984
Itzik984

Reputation: 16794

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?

Upvotes: 3

Views: 874

Answers (2)

whodini9
whodini9

Reputation: 1434

You should always use path = File.join("C:","Program Files","Blah") To ensure it works on any architecture.

Upvotes: -1

peter
peter

Reputation: 42207

  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.

Upvotes: 2

Related Questions