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

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:

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

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

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

Related: IO#pos=, IO#tell.