3.5 Input and Output

Output Using Variables

Displaying text in Ruby is simple. Try entering the following at the command prompt:

irb(main):001:0> puts "Hello World"

The puts method (short for outPUT a String) simply displays a string on the screen. Notice the string is contained in quotation marks; otherwise, both Hello and World would be interpreted as variables. Variables are displayed on the screen using similar syntax, except without quotation marks:

irb(main):002:0> text = "Hello World"
=> "Hello World"
irb(main):003:0> puts text
=> Hello World

This example stores the string “Hello World” in a variable named text and then displays the value stored in the text variable using the puts method. This method is not limited to strings and can be used with other classes including integers, floats, and Booleans.

The use of classes to define data types means a variety of methods can be done for each type. For example, x.length indicates the size of a string when x is defined as a string.

Display User Input

Displaying user input in Ruby is almost as easy as displaying output. Try entering the following in the command prompt:

irb(main):001:0> age_input = gets

The gets method (short for GET a String from the user) stops the program and waits for the user to type some text and then press Enter. The text typed by the user will be stored as a string in a variable called age_input. Due to the nature of the gets method, the value stored in age_input will be a string, but you need ...

Get Computer Science Programming Basics in Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.