ruby - 为什么这个简单的 Ruby 程序没有打印出我期望的结果?

标签 ruby temporary-files

我有这个:

require 'tempfile'
t = Tempfile.new('test-data')
t.open
t.sync = true
t << "apples"
t.puts "bananas"
puts "contents are [#{t.read}] (#{t.size} bytes)"
t.close

这打印:

contents are [] (14 bytes)

为什么没有实际显示内容?我在使用 Ruby 1.9.2。

最佳答案

问题是您正在文件中的当前 IO 指针处执行 read,该指针在您写入后已经位于末尾。您需要在 read 之前执行 rewind。在你的例子中:

require 'tempfile'
t = Tempfile.new('test-data')
t.open
t.sync = true
t << "apples"
t.puts "bananas"
t.rewind
puts "contents are [#{t.read}] (#{t.size} bytes)"
t.close

关于ruby - 为什么这个简单的 Ruby 程序没有打印出我期望的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2925093/

相关文章:

stata - 删除临时文件

ruby-on-rails - ROR/Hpricot : parsing a site and searching/comparing strings with regex

ruby - 组合多个 'elsif' 语句

ruby-on-rails - Ruby 通用文件系统库

ruby-on-rails - 尝试从 Rails 应用程序在 redmine 上创建问题

python - Django TemporaryUploadedFile 不存在,但它被成功读取

管道与临时文件

java - 正在运行的 Ruby 和 Java 程序之间进行通信

java - 我是否需要删除由我的 java 应用程序创建的 tmp 文件?

visual-studio - 如何防止 Visual Studio 在我的源目录中创建 obj 文件夹?