对此有很多 SO 答案,例如“How to write to file in Ruby?”,但我遗漏了一个带有文件路径
的点:
我的文件结构是这样的:
├── test.txt
├── write_to_file.rb
和“write_to_file.rb”有以下内容:
File.open('test.txt', 'w') { |file| file.write('hello') }
# tried ('./test.txt','w') ..as well.
如何将一些内容从另一个 write_to_file.rb
写入到 test.txt
文件?
最佳答案
正确的做法:
file = File.join(File.dirname(__FILE__), 'test.txt')
File.open(file, 'w') { |f| f.puts 'hello' }
__FILE__
是包含上述代码的文件的路径,因为,您的 test.txt
与 write_to_file.rb
位于同一目录中, 无论您在计算机上的哪个目录中,这都应该有效。
另请注意,我使用了 puts
方法而不是 write
,因为我更喜欢换行符。 :)
您的代码有什么问题(可能):
当您使用 test.txt
时, 那么该路径是相对于您运行 write_to_file.rb
的目录的脚本。例如,如果您运行 write_to_file.rb
从你的主目录,然后 test.txt
将暗示 ~/test.txt
.
关于ruby - 如何在 Ruby 中写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20791024/