Menu
Coddy logo textTech

Input with gets

Part of the Fundamentals section of Coddy's Ruby journey — lesson 29 of 88.

So far, you've learned how to display output. Now let's learn how to receive input from the user. The gets method reads a line of text that the user types in.

name = gets
puts "Hello, #{name}"

When Ruby encounters gets, it waits for the user to type something and press Enter. Whatever they type gets stored in the variable. If the user types "Alice", the output would be:

Hello, Alice

There's something important to notice here. When the user presses Enter, that newline character gets included in the input.

That's why "Alice" appears with an extra blank line after it. The variable actually contains "Alice\n" where \n represents the newline.

You can use p to see this clearly:

name = gets
p name

If the user types "Ruby", the output shows:

"Ruby\n"

This trailing newline can cause unexpected behavior in your programs. In the next lesson, you'll learn how to remove it.

challenge icon

Challenge

Easy

Read a name from the user using gets and store it in a variable called name.

Then use p to output the name variable, which will show the raw string including the trailing newline character.

For example, if the input is Ruby, your output should display the string with its quotation marks and the \n character visible.

Cheat sheet

The gets method reads user input from the console:

name = gets
puts "Hello, #{name}"

When gets is executed, the program waits for the user to type something and press Enter. The input is stored in the variable.

The gets method includes the newline character (\n) when the user presses Enter:

name = gets
p name
# If user types "Ruby", outputs: "Ruby\n"

Use p to display the raw string representation, which shows the newline character explicitly.

Try it yourself

# TODO: Read a name from the user using gets and store it in a variable called name


# TODO: Use p to output the name variable
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals