Skip to content

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

instance method

Pathname#write

(::String content, ?::Integer offset, ?mode: ::Integer | ::String, ?flags: ::Integer, ?external_encoding: ::encoding, ?internal_encoding: ::encoding, ?encoding: ::encoding, ?textmode: ::boolish, ?binmode: ::boolish, ?autoclose: ::boolish) -> ::Integer
write(data, offset = 0, **opts) → nonnegative_integer

Opens the file at self.to_s, writes the given data to it, and closes the file; returns the number of bytes written.

With only argument data given, writes the given data to the file:

Example
path = 't.tmp'
pn = Pathname.new(path)
pn.write('foo') # => 3
File.read(path) # => "foo"

If offset is zero (the default), the file is overwritten:

Example
pn.write('bar')
File.read(path) # => "bar"

If offset in within the file content, the file is partly overwritten:

Example
pn.write('foobarbaz')
pn.write('BAR', 3)
File.read(path) # => "fooBARbaz"

If offset is outside the file content, the file is padded with null characters "\u0000":

Example
pn.write('bat', 12)
File.read(path) # => "fooBARbaz\u0000\u0000\u0000bat"

Optional keyword arguments opts specify:

See also #writable_real? #zero? #writable? also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0