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
io.c
View on GitHub ↗
VALUE
rb_io_ungetbyte(VALUE io, VALUE b)
{
rb_io_t *fptr;
GetOpenFile(io, fptr);
rb_io_check_byte_readable(fptr);
switch (TYPE(b)) {
case T_NIL:
return Qnil;
case T_FIXNUM:
case T_BIGNUM: ;
VALUE v = rb_int_modulo(b, INT2FIX(256));
unsigned char c = NUM2INT(v) & 0xFF;
b = rb_str_new((const char *)&c, 1);
break;
default:
SafeStringValue(b);
}
io_ungetbyte(b, fptr);
return Qnil;
}
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
rewindon 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