Skip to content

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

instance method

IO#ungetc

ungetc(integer) → nil
ungetc(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 Character 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, interprets the integer as a character:

Example
File.write('t.tmp', '012')
f = File.open('t.tmp')
f.ungetc(0x41)     # => nil
f.read             # => "A012"
f.rewind
f.ungetc(0x0442)   # => nil
f.getc.ord         # => 1090
f.close

When argument string is given, uses all characters:

Example
File.write('t.tmp', '012')
f = File.open('t.tmp')
f.ungetc('A')      # => nil
f.read      # => "A012"
f.rewind
f.ungetc("\u0442\u0435\u0441\u0442") # => nil
f.getc.ord      # => 1090
f.getc.ord      # => 1077
f.getc.ord      # => 1089
f.getc.ord      # => 1090
f.close
See also #ungetbyte #wait #tty? #wait_priority also in 4.1 · 4.0 · 3.4 · 3.2 · 3.1 · 3.0