Ruby 如何写入临时文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18052966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:28:23  来源:igfitidea点击:

Ruby how to write to Tempfile

ruby-on-railsrubyfile-io

提问by Siva

I am trying to create a Tempfile and write some text into it. But I get this strange behaviour in rails console

我正在尝试创建一个临时文件并向其中写入一些文本。但是我在 rails 控制台中得到了这种奇怪的行为

t = Tempfile.new("test_temp") # => #<File:/tmp/test_temp20130805-28300-1u5g9dv-0>
t << "Test data"              # => #<File:/tmp/test_temp20130805-28300-1u5g9dv-0>
t.write("test data")          # => 9
IO.read t.path                # => ""

I also tried cat /tmp/test_temp20130805-28300-1u5g9dv-0but the file is empty

我也试过了,cat /tmp/test_temp20130805-28300-1u5g9dv-0但是文件是空的

Am I missing anything ? Or what's the proper way to write to Tempfile?

我错过了什么吗?或者写信的正确方法是Tempfile什么?

FYI I'm using ruby 1.8.7 and rails 2.3.12

仅供参考,我正在使用 ruby​​ 1.8.7 和 rails 2.3.12

回答by squiguy

You're going to want to close the temp file after writing to it. Just add a t.closeto the end. I bet the file has buffered output.

在写入临时文件后,您将要关闭它。只需t.close在末尾添加一个。我敢打赌该文件已缓冲输出。

回答by Debadatt

Try this run t.rewindbefore read

t.rewind在阅读之前尝试此运行

require 'tempfile'
t = Tempfile.new("test_temp")
t << "Test data"
t.write("test data") # => 9
IO.read t.path # => ""
t.rewind
IO.read t.path # => "Test datatest data"

回答by Lev Lukomsky

closeor rewindwill actually write out content to file. And you may want to delete it after using:

close或者rewind实际上将内容写入文件。您可能想在使用后将其删除:

file = Tempfile.new('test_temp')
begin
  file.write <<~FILE
    Test data
    test data
  FILE
  file.close

  puts IO.read(file.path) #=> Test data\ntestdata\n
ensure
  file.delete
end

回答by Artur Beljajev

It's worth mentioning, calling .rewindis a must, or any subsequent .readcall will just return empty value

值得一提的是,调用.rewind是必须的,否则任何后续.read调用都只会返回空值