Ruby IO#read and bytesize
An IO read can return fewer bytes than requested at the end of a stream.
A simple example
IO#read and bytesize
- Start with One available byte
- Do this Try to read a complete two-byte field
- Result One byte is missing
Syntax
record.bytesize == 4
Run these examples in Ruby
Save one example at a time as lesson.rb. Use Ruby 2.6 or later.
ruby lesson.rbRead a stock count from a short record
A stock scanner sends each count as a four-byte integer. A transfer stops after two bytes, so the receiver must request the record again before posting the count to inventory.
require "stringio"
record = StringIO.new("\x00\x05").read(4)
if record && record.bytesize == 4
puts record.unpack1("N")
else
puts "Request the complete record"
end
Request the complete record
The two-byte transfer falls short of the four bytes required for a stock count.
Decode a complete gate count
A counter sends one four-byte record for the entrance. The device format requires a four-byte integer. Request another transmission if the input ends before all four bytes arrive.
Detect a cut-off meter record
A sensor connection closes after the first two bytes of a four-byte record. The device format requires a four-byte integer. Request another transmission if the input ends before all four bytes arrive.
What to watch for
An empty stream can return nil. Check for both nil and a short record before unpacking.