Method: IO#ungetbyte

Defined in:
io.c

#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:

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:

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

Overloads:

  • #ungetbyte(integer) ⇒ nil

    Returns:

    • (nil)
  • #ungetbyte(string) ⇒ nil

    Returns:

    • (nil)
[View source]

5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
# File 'io.c', line 5171

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:
        StringValue(b);
    }
    io_ungetbyte(b, fptr);
    return Qnil;
}