Method: IO#seek

Defined in:
io.c

#seek(offset, whence = IO::SEEK_SET) ⇒ 0

Seeks to the position given by integer offset (see Position) and constant whence, which is one of:

  • :CUR or IO::SEEK_CUR: Repositions the stream to its current position plus the given offset:

    f = File.open('t.txt')
    f.tell            # => 0
    f.seek(20, :CUR)  # => 0
    f.tell            # => 20
    f.seek(-10, :CUR) # => 0
    f.tell            # => 10
    f.close
    
  • :END or IO::SEEK_END: Repositions the stream to its end plus the given offset:

    f = File.open('t.txt')
    f.tell            # => 0
    f.seek(0, :END)   # => 0  # Repositions to stream end.
    f.tell            # => 52
    f.seek(-20, :END) # => 0
    f.tell            # => 32
    f.seek(-40, :END) # => 0
    f.tell            # => 12
    f.close
    
  • :SET or IO:SEEK_SET: Repositions the stream to the given offset:

    f = File.open('t.txt')
    f.tell            # => 0
    f.seek(20, :SET) # => 0
    f.tell           # => 20
    f.seek(40, :SET) # => 0
    f.tell           # => 40
    f.close
    

Related: IO#pos=, IO#tell.

Returns:

  • (0)


2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
# File 'io.c', line 2515

static VALUE
rb_io_seek_m(int argc, VALUE *argv, VALUE io)
{
    VALUE offset, ptrname;
    int whence = SEEK_SET;

    if (rb_scan_args(argc, argv, "11", &offset, &ptrname) == 2) {
        whence = interpret_seek_whence(ptrname);
    }

    return rb_io_seek(io, offset, whence);
}