Home > Software engineering >  Ruby creating file in home directory instead of current one
Ruby creating file in home directory instead of current one

Time:04-01

I'm running my program in a directory with the following path:

/home/user/Desktop/Ruby/Projects/event_manager/lib,

trying to accomplish the following:

Dir.mkdir('output') unless Dir.exist?('output')
filename = "output/thanks.html"

Working well, however it does create the folder in my /home/user directory, and then in it creates this .html file, instead of the directory I run the program in. I always have to type the full path to the directory I'm in whenever I wanna create a new directory or files. How may it be changed to create the files in this specific /lib directory and not having to type the paths manually? Moreover, whenever I try to run, for instance:

blahblah = File.read('noodles.html')

The program recognizes that this particular noodles.html file actually IS in the current directory and reads it perfectly.

CodePudding user response:

You should get the current directory path and concat with filename.

Try this code, it should solve the problem.

dirname = 'output'
Dir.mkdir(dirname) unless Dir.exist?(dirname)
filename = "thanks.html"
filepath = "#{Dir.pwd}/#{dirname}/#{filename}" # Dir.pwd to get current irb directory
blahblah = File.read(filepath)

Hope it helps

  • Related