Search code examples
rubytemporary-files

Why doesn't this simple Ruby program print what I expect it to?


I have this:

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

This prints:

contents are [] (14 bytes)

Why aren't the contents actually shown? I'm on Ruby 1.9.2.


Solution

  • You are probably at the end of the stream, where there are no more bytes left. After writing and before reading you should rewind the file (reopen or seek to position 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