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
file.c
View on GitHub ↗
static VALUE
rb_file_truncate(VALUE obj, VALUE len)
{
rb_io_t *fptr;
struct ftruncate_arg fa;
fa.pos = NUM2OFFT(len);
GetOpenFile(obj, fptr);
if (!(fptr->mode & FMODE_WRITABLE)) {
rb_raise(rb_eIOError, "not opened for writing");
}
rb_io_flush_raw(obj, 0);
fa.fd = fptr->fd;
if ((int)rb_io_blocking_region(fptr, nogvl_ftruncate, &fa) < 0) {
rb_sys_fail_path(fptr->pathv);
}
return INT2FIX(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)