Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
The IO Class
3.
Opening Files
3.1.
File.open
3.2.
Kernel.open
3.3.
StringIO
4.
Writing to the Console in Ruby
4.1.
Print and puts method
4.2.
p, putc and printf methods
5.
Reading from the console in Ruby
5.1.
$stdin.read
5.2.
gets method
5.3.
chomp method
6.
Frequently Asked Questions
6.1.
What is an IO object?
6.2.
How can we input an integer in Ruby?
6.3.
What is the difference between puts and print in Ruby?
6.4.
Why does puts returns nil in Ruby?
6.5.
How do you input in Ruby?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Input and Output in Ruby

Author Abhay Trivedi
0 upvote

Introduction

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.

Input and Output in Ruby

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
Run Code


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
Run Code

StringIO

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
Run Code

 

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.

$stdout.print "Ruby language\n"
print "Apple "
print "Apple\n"

puts "Orange"
puts "Orange"
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

Ruby Language
Apple Apple
Orange
Orange
You can also try this code with Online Ruby Compiler
Run Code

 

Text output is produced on the console through the print and puts functions. The latter adds a new line character, making the two different.

p, putc and printf methods

There are three additional ways to print output in Ruby.

p "Lemon"
p "Lemon"

printf "There are %d apples\n", 3

putc 'K'
putc 0xA
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

"Lemon"
"Lemon"
There are 3 apples
K
You can also try this code with Online Ruby Compiler
Run Code

 

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
Run Code

 

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
Run Code

 

Output:

Enter your name: John
Hello John

chomp method

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
Run Code

 

Output:

Enter a string: Ruby
The string has 4 characters

Frequently Asked Questions

What is an IO object?

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 RubyRuby coding NinjasDocumentationOfficial Ruby FAQ, and Ruby Koans.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc; you must look at the problems, interview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Thankyou form Coding Ninjas

Live masterclass