End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
IO.write
static VALUE
rb_io_s_write(int argc, VALUE *argv, VALUE io)
{
return io_s_write(argc, argv, io, 0);
}
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
selfis 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:
IO.write('| cat', 'Hello World!') # => 12
Output:
Hello World!
With argument path given, writes the given data to the file at that path:
IO.write('t.tmp', 'abc') # => 3 File.read('t.tmp') # => "abc"
If offset is zero (the default), the file is overwritten:
IO.write('t.tmp', 'A') # => 1 File.read('t.tmp') # => "A"
If offset in within the file content, the file is partly overwritten:
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":
IO.write('t.tmp', 'xyz', 10) # => 3 File.read('t.tmp') # => "ab012f\u0000\u0000\u0000\u0000xyz"
Optional keyword arguments opts specify: