【问题标题】:Why doesn't this simple Ruby program print what I expect it to?为什么这个简单的 Ruby 程序不能打印出我期望的结果?
【发布时间】:2011-02-24 21:19:42
【问题描述】:

我有这个:

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 上。

【问题讨论】:

标签: ruby temporary-files


【解决方案1】:

问题是您正在文件中的当前 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

【讨论】:

    【解决方案2】:

    您可能处于流的末尾,没有更多字节了。写完之后读之前你应该倒回文件(重新打开或寻找位置 0)。

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

    【讨论】:

    • 杜尔。是的,添加 #close#open 固定的东西。这是写后阅读的惯用方式还是我应该改用seek(0)
    • 您应该考虑多件事情:首先并不是所有的 IO 对象都可以被寻找,因此重新打开有时是唯一的选择。但是 Tempfile 类在关闭它之后(以及在 GC 之后)删除创建的文件,并且在重新打开它的小时间范围内,其他进程可能会处理它,这使得重新打开更容易出错。
    猜你喜欢
    • 2018-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-15
    相关资源
    最近更新 更多