How to Use the Ruby write Method

09/26/2021

Contents

In this article, you will learn how to use the Ruby write method.

Using the write method

The write method in Ruby is a built-in method of the IO class, which allows you to write data to an output stream, such as a file or standard output. The write method takes a single argument, which is the data to be written to the output stream.

Syntax

The basic syntax for using the write method is as follows:

output_stream.write(data)

Here, output_stream is an instance of the IO class, and data is the data to be written to the stream. The write method returns the number of bytes that were written to the stream.

Examples

For example, to write the string “Hello, world!” to standard output, you can use the following code:

puts "Writing to standard output..."
$stdout.write("Hello, world!\n")

In this example, the $stdout global variable represents the standard output stream, and the write method is used to write the string “Hello, world!” to the stream. The \n at the end of the string is a newline character, which adds a line break after the string is written to the output stream.

If you want to write data to a file, you can use the File class to open the file and create an output stream. Here’s an example:

puts "Writing to file..."
file = File.open("output.txt", "w")
file.write("Hello, file!\n")
file.close

In this example, the File.open method is used to open the file “output.txt” in write mode (“w”), which creates an output stream that can be used to write data to the file. The write method is then used to write the string “Hello, file!” to the stream. Finally, the close method is called to close the output stream and flush any remaining data to the file.

It’s important to note that the write method overwrites any existing data in the output stream or file. If you want to append data to the end of a file, you can use the << (append) operator instead of the write method:

puts "Appending to file..."
file = File.open("output.txt", "a")
file << "More data!\n"
file.close

In this example, the File.open method is used to open the file "output.txt" in append mode ("a"), which creates an output stream that appends data to the end of the file. The << operator is then used to append the string "More data!" to the stream. Finally, the close method is called to close the output stream and flush any remaining data to the file.