Skip to content

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

class method

IO.write

(::path path, ::_ToS data, ?::Integer offset, ?external_encoding: ::String | ::Encoding | nil, ?internal_encoding: ::String | ::Encoding | nil, ?encoding: ::String | ::Encoding | nil, ?textmode: ::boolish, ?binmode: ::boolish, ?autoclose: ::boolish, ?mode: ::String) -> ::Integer
IO.write(path, data, offset = 0, **opts) → nonnegative_integer

Opens the stream, writes the given data to it, and closes the stream; returns the number of bytes written.

The first argument must be a string that is the path to a file.

With only arguments path and data given, writes the given data to the file at that path:

Example
path = 't.tmp'
File.write(path, "First line\nSecond line\n\nFourth line\nFifth line\n") # => 47
File.write(path, 'こんにちは')                                             # => 15
File.write(path, "\xFE\xFF\x99\x90\x99\x91\x99\x92\x99\x93\x99\x94")     # => 12

When offset is zero (the default), the entire file content is overwritten:

Example
File.read(path) # => "\xFE\xFF\x99\x90\x99\x91\x99\x92\x99\x93\x99\x94"
File.write(path, 'foo')
File.read(path) # => "foo"

When offset in within the file content, the file content is partly overwritten, beginning at byte offset:

Example
File.write(path, "First line\nSecond line\n\nFourth line\nFifth line\n")
File.write(path, 'LINE', 6)
File.read(path) # => "First LINE\nSecond line\n\nFourth line\nFifth line\n"

When the file contains multi-byte characters, the effect of writing may disturb some characters:

Example
File.write(path, "こんにちは")
File.write(path, 'FOO', 3)  # Replace one 3-byte character.
File.read(path) # => "こFOOにちは"
File.write(path, 'BAR', 7)  # Replace bytes in two different 3-byte characters.
File.read(path) # => "こFOO\xE3BAR\x81\xA1は"

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

Example
File.write(path, "First line\nSecond line\n\nFourth line\nFifth line\n")
File.write(path, 'FOO', 55)
File.read(path)
# => "First line\nSecond line\n\nFourth line\nFifth line\n\u0000\u0000\u0000FOO"

Optional keyword arguments opts specify:

See also #write .try_convert #<< .sysopen also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0