How to Accept User Input With Gets in Ruby

Nurudeen Ibrahim Feb 02, 2024
How to Accept User Input With Gets in Ruby

When building a Command Line (CLI) application in Ruby, one common functionality is receiving input from users, including a user’s name or a yes/no response. This is where the gets keyword is useful.

This tutorial will show how to build a very simple CLI program that allows users to input their names and greet them using the name they’ve entered.

Example code:

puts 'Hi, welcome to my app.'
puts 'Enter your name to get started: '
name = gets
puts "Hello #{name}, nice to have you here"

Output:

Hi, welcome to my app.
Enter your name to get started:

Above is the output I get after running the code. At this point, the program is asking me to enter my name. This is what gets does; it creates a prompt and awaits user input.

Below is the complete output I get after entering my name as John and pressing the Enter key.

Hi, welcome to my app.
Enter your name to get started:
John
Hello John
, nice to have you here

You must have noticed something weird in the output above. Why did the greeting, Hello John, nice to have you here break after John? To understand what’s really happening, inspect the variable name.

Example code:

puts 'Hi, welcome to my app.'
puts 'Enter your name to get started: '
name = gets
puts name.inspect
puts "Hello #{name}, nice to have you here"

Output:

Hi, welcome to my app.
Enter your name to get started:
John
"John\n"
Hello John
, nice to have you here

Above is the complete output I get after entering John as my name. You can see that the name variable shows up as John\n.

That’s how gets behaves; it automatically appends \n to whatever value it receives as user input, this is called the newline character, and whenever it appears in a text, it means the text should break at that point, and continue on a new line.

A good way of fixing this is to use the chomp method, which removes any trailing special character, not only the newline character (\n) but also the carriage return character (\r). You can read more here about how chomp works.

Example code:

puts 'Hi, welcome to my app.'
puts 'Enter your name to get started: '
name = gets.chomp
puts "Hello #{name}, nice to have you here"

Output:

Hi, welcome to my app.
Enter your name to get started:
John
Hello John, nice to have you here