Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

File#truncate

(::int length) -> 0
truncate(size) → 0

Adjusts the size of self to the given size, regardless of the current position; does not adjust the position:

Example
filepath = '/tmp/t.tmp'
file = File.new(filepath, 'w+')
file.write('0123456789')
file.truncate(5)
file.pos  # => 10
file.rewind
file.read # => "01234"

Pads with null characters if necessary:

Example
file.truncate(10)
file.pos  # => 5
file.rewind
file.read # => "01234\u0000\u0000\u0000\u0000\u0000"
# Clean up.
file.close
File.delete(filepath)
See also .truncate #size #mtime also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0