简体   繁体   中英

How to write output file of ruby code into specific directory/location?

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.

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM