0

I have ruby code which will create output file, currently file is creating at location from where my script is running. I have to write output file to different location so i am specifying explicit path into code. but it's not able to create file. my code looks like :

fname = "C:\repo\cookbooks\abc\recipes\add.rb"
somefile = File.open(fname,"w")  
somefile.puts "end"
somefile.close

If i specify

fname = "add.rb"

it's working but i want to create it at different location as i mentioned above code in C:\ drive.

1 Answer 1

1

Because \ in strings are special characters so you should use \\ (double backslashes) to get a single backslash. But there is a better way, you don't need to deal with backslashes at all:

fname = File.join("C:", "repo", "cookbooks", "abc", "recipes", "add.rb")
Sign up to request clarification or add additional context in comments.

3 Comments

As far as I know you can also use / instead and it'll be converted automatically, or you can use single quotes to avoid the issue entirely.
Yep, there are other ways :)
In particular, \r is a CARRIAGE RETURN.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.