Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

IO#ungetbyte

ios.ungetbyte(string) → nil
ios.ungetbyte(integer) → nil

Pushes back bytes (passed as a parameter) onto ios, such that a subsequent buffered read will return it. It is only guaranteed to support a single byte, and only if ungetbyte or ungetc has not already been called on ios since the previous read of at least a single byte from ios. However, it can support additional bytes if there is space in the internal buffer to allow for it.

Example
f = File.new("testfile")   #=> #<File:testfile>
b = f.getbyte              #=> 0x38
f.ungetbyte(b)             #=> nil
f.getbyte                  #=> 0x38

If given an integer, only uses the lower 8 bits of the integer as the byte to push.

Example
f = File.new("testfile")   #=> #<File:testfile>
f.ungetbyte(0x102)         #=> nil
f.getbyte                  #=> 0x2

Calling this method prepends to the existing buffer, even if the method has already been called previously:

Example
f = File.new("testfile")   #=> #<File:testfile>
f.ungetbyte("ab")          #=> nil
f.ungetbyte("cd")          #=> nil
f.read(5)                  #=> "cdab8"

Has no effect with unbuffered reads (such as IO#sysread).

See also #tty? #ungetc #to_io #wait also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0