我有这个:
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/