Input and Output in Ruby generally refer to reading files, printing information on the console, and dealing with the network sockets. Any information that a program reads from a keyboard, file, or other program is considered input, whereas the data that the program produces is called output. Output can go to the screen, a file, or another program.
In the following article, we will learn about these operations of Input and Output in Ruby and how to perform them. We will also dive deeper into various file input and output methods provided by Ruby along with their implementation.
The IO Class
The foundation of all input and output in Ruby is the IO class. The subclass of the IO class is the File class which is responsible for the file Input/output operations. These two classes have a lot in common.
Opening Files
To Input and Output in Ruby, we first need to open a file to. Here are the methods which may help you to do so.
File.open
Reading and writing a file is one of the most fundamental IO operations. The File class defines a few utility methods that read a file's entire contents in a single call. To read from or write to a file, we frequently use IO methods to obtain a File object after opening a file.
The following code depicts the opening of files and performing read-write operations on them.
f = File.open("data.txt", "r") # Open file data.txt for reading
out = File.open("out.txt", "w") # Open file out.txt for writing T
You can also try this code with Online Ruby Compiler
The first argument specifies the file name, whereas the second argument designates the file mode. The following table gives the list of different file modes we can use.
Mode
Description
“r”
Open for reading. The default mode.
“r+”
Open for reading and writing. Start at the beginning of the file. Fail if the file does not exist.
“w”
Open for writing. Create a new file or truncate an existing one.
“w+”
Like "w", but allows reading of the file as well.
“a”
Open for writing, but append to the end of the file if it already exists.
“a+”
Like "a", but allows reads also
Kernel.open
The Kernel method open is similar to File.open but works more flexibly. The returned stream reads from and writes to the operating system command process if the filename starts with |, which is considered an operating system command. Obviously, this feature depends on the platform.
If the open-uri library has been loaded, then open can also be used to read from HTTP and FTP URLs as if they were files:
require "open-uri" # Required library
f = open("http://www.davidflanagan.com/") # Webpage as a file
webpage = f.read # Read it as one big string
f.close # close the file
You can also try this code with Online Ruby Compiler
Using the stringio library to read from or write to a string is another option to obtain an IO object:
require "stringio"
input = StringIO.open("now is the time") # Read from this string
buffer = ""
output = StringIO.open(buffer, "w") # Write into buffer
You can also try this code with Online Ruby Compiler
Even if the IO class is not a subclass of StringIO, it defines many of the same methods as IO. Duck typing typically enables us to use a StringIO object instead of an IO object.
Writing to the Console in Ruby
There are various ways to print output on the console with Ruby. The Kernel module contains these methods. All objects in Ruby have access to the Kernel's methods.
Print and puts method
The $stdout.print equivalent is the print method. The standard output stream is stored in the global variable $stdout.
We demonstrate the p, printf, and putc methods in the example.
When the object is printed, the p calls the inspect method. The technique is practical for debugging.
The printf method is famous from the C programming language. It makes string formatting possible.
One character is printed to the console with the putc method. A newline is printed on the second line as shown in the example. The newline character's hexadecimal code is 0xA.
Reading from the console in Ruby
Reading from the console is also important for Input and Output in Ruby.
$stdin.read
The standard input stream is stored in the global variable $stdin. It can be used to read console input.
inp = $stdin.read
puts inp
You can also try this code with Online Ruby Compiler
Up until the file's end, the read method reads data from the standard input. Pressing Ctrl+D in Unix or Ctrl+Z in Windows will result in the end of Input.
gets method
The gets method is frequently used to read data from the console.
print "Enter your name: "
name = gets
puts "Hello #{name}"
You can also try this code with Online Ruby Compiler
The chomp method is a string method that gets rid of blank spaces at the end of strings. It is helpful while performing input processes, The Perl programming language inspired the method's name and syntax.
print "Enter a string: "
inp = gets.chomp
puts "The string has #{inp.size} characters"
You can also try this code with Online Ruby Compiler
An IO object is a two-way communication path between a Ruby program and an outside resource.
How can we input an integer in Ruby?
We can use the get.chomp.to_i function in Ruby to request user-provided integer inputs. The class of the variable holding gets.chomp in is Fixnum, demonstrating that an is an integer.
What is the difference between puts and print in Ruby?
The results of evaluating Ruby code are shown in the console using the commands puts (short for "out*put s*tring") and print. The main distinction between them is that puts, unlike print, add a new line after it has been executed.
Why does puts returns nil in Ruby?
Not simply a keyword, but a real Ruby object, nil, stands for nothing. A method returns nil whenever it doesn't produce a useful value.
How do you input in Ruby?
The gets method in Ruby makes it possible to accept user input. The terminal is prepared for user input when a line containing the gets method is read during the execution of a Ruby program.
Conclusion
In this article, we have extensively discussed the Input and Output in Ruby. We began with File IO Operations and then explored various ways in which we can take and read input from the console in Ruby.
After reading about Input and Output in Ruby, are you not feeling excited to read/explore more articles on the Ruby language? Don't worry; Coding Ninjas has you covered. To learn, see Ruby, Ruby coding Ninjas, Documentation, Official Ruby FAQ, and Ruby Koans.