1. Computing
Send to a Friend via Email

Overlooking Input and Output? Using the Input / Output Methods in Ruby

Using "gets" and "puts" for Input / Output

By

At the heart of any command-line interface is input and output. Without the ability to print things to the terminal and read input from the keyboard, a command-line interface is crippled. The primary methods in Ruby to accomplish this are puts or "put string" to write to the terminal and gets or "get string" to read from the keyboard.

Output

While puts is one of the most common output methods in Ruby code (especially example code), its proper use is often overlooked. The puts method takes any number of arguments. For each argument, puts will look at the object's type. If the object is of the String type, puts will print it to the terminal followed by a newline. If the object is of the Array type, puts will iterate over the elements of the array and print each, followed by a newline. For objects of all other types, puts will first call the object's to_s method which attempts to convert the object to a string, then prints the result of to_s followed by a newline. If puts is called with no arguments, it will print a single newline.

The following example illustrates several uses of puts. Single strings are printed, single objects of a custom type are printed, multiple strings and objects a printed, arrays are printed and puts is used alone to separate each example with an extra newline.

 #!/usr/bin/env ruby
 
 puts "Testing puts"
 puts # Extra newline
 
 puts "Testing", "one", "two", "three"
 puts
 
 puts "Testing", [ "one", "two", "three" ]
 puts
 
 class TestClass
 end
 
 puts TestClass.new
 

Input

The gets method for input is as equally overlooked as the puts method for output. The gets method will read a single line from the keyboard and return it. A "line" is defined by a string of characters followed by the "record separator." The default record separator is the newline, but a different record separator can be passed as a single argument to the gets method. In addition to returning the string read from the keyboard, gets also assigns this string to the special $_ variable.

The following example reads a variety of strings from the keyboard. First, an entire line is read. Note that the idiom gets.chomp is used. The string returned by gets still has the record separator attached, so the chomp method will remove it. Secondly in this example, individual elements from a comma-separated list are read from the keyboard. Again, chomp is used to remove the record separator (in this case, a comma).

 #!/usr/bin/env ruby
 
 print "Enter your name: "
 name = gets.chomp
 puts "Hello #{name}"
 
 print "Enter your some more names separated by commas: "
 while true
   name = gets(',').chomp(',')
   puts "Hello #{name}"
 end
 

©2014 About.com. All rights reserved.