Skip to content

End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

class method

IO.write

IO.write(command, data, **opts) → integer
IO.write(path, data, offset = 0, **opts) → integer

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

When called from class IO (but not subclasses of IO), this method has potential security vulnerabilities if called with untrusted input; see Command Injection.

The first argument must be a string; its meaning depends on whether it starts with the pipe character ('|'):

  • If so (and if self is IO), the rest of the string is a command to be executed as a subprocess.

  • Otherwise, the string is the path to a file.

With argument command given, executes the command in a shell, passes data through standard input, writes its output to $stdout, and returns the length of the given data:

Example
IO.write('| cat', 'Hello World!') # => 12

Output:

Example
Hello World!

With argument path given, writes the given data to the file at that path:

Example
IO.write('t.tmp', 'abc')    # => 3
File.read('t.tmp')          # => "abc"

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

Example
IO.write('t.tmp', 'A')      # => 1
File.read('t.tmp')          # => "A"

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

Example
IO.write('t.tmp', 'abcdef') # => 3
File.read('t.tmp')          # => "abcdef"
# Offset within content.
IO.write('t.tmp', '012', 2) # => 3
File.read('t.tmp')          # => "ab012f"

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

Example
IO.write('t.tmp', 'xyz', 10) # => 3
File.read('t.tmp')           # => "ab012f\u0000\u0000\u0000\u0000xyz"

Optional keyword arguments opts specify:

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