Ruby 在主目录而不是当前目录中创建文件

Ruby creating file in home directory instead of current one

我运行将我的程序放在具有以下路径的目录中:

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

正在尝试完成以下任务:

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

工作正常,但它确实在我的 /home/user 目录中创建了文件夹,然后在其中创建了这个 .html 文件,而不是我 运行 程序所在的目录. 每当我想创建一个新目录或文件时,我总是必须输入我所在目录的完整路径。如何更改以在这个特定的 /lib 目录中创建文件而不必手动键入路径?此外,每当我尝试 运行 时,例如:

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

程序识别出这个特定的 noodles.html 文件实际上在当前目录中并且可以完美地读取它。

您应该获取当前目录路径并与文件名连接。

试试这个代码,它应该可以解决问题。

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)

希望对您有所帮助