Skip to content

Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

IO#ungetbyte

ungetbyte(integer) → nil
ungetbyte(string) → nil

Pushes back (“unshifts”) the given data onto the stream’s buffer, placing the data so that it is next to be read; returns nil. See Byte IO.

Note that:

  • Calling the method has no effect with unbuffered reads (such as IO#sysread).

  • Calling rewind on the stream discards the pushed-back data.

When argument integer is given, uses only its low-order byte:

Example
File.write('t.tmp', '012')
f = File.open('t.tmp')
f.ungetbyte(0x41)   # => nil
f.read              # => "A012"
f.rewind
f.ungetbyte(0x4243) # => nil
f.read              # => "C012"
f.close

When argument string is given, uses all bytes:

Example
File.write('t.tmp', '012')
f = File.open('t.tmp')
f.ungetbyte('A')    # => nil
f.read              # => "A012"
f.rewind
f.ungetbyte('BCDE') # => nil
f.read              # => "BCDE012"
f.close
See also #tty? #ungetc #to_path #wait also in 4.1 · 4.0 · 3.4 · 3.2 · 3.1 · 3.0