Cleaning Up User Input

Learn to Program, Third Edition — by Chris Pine (27 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Getting Strings from the User | TOC | Good Variable Names 👉

Let’s make a program that greets you by name. Write the following program:

​1: puts ​"Hello there, and what's your name?"​ 
​2: name = gets
​3: puts ​"Your name is ​​#{​name​}​​? What a lovely name!"​
​4: puts ​"Pleased to meet you, ​​#{​name​}​​. :)"​

I ran it, and this is what happened:

​<= Hello there, and what's your name?
​=> ​Chris​
​<= Your name is Chris
​ ? What a lovely name!
​ Pleased to meet you, Chris
​ . :)

Yikes! This program first prompts for a name, and then it prints a message. But something’s wrong. When I typed the letters C, h, r, i, and s, and then pressed Enter, the gets method got all of the letters in my name and the Enter. Well, that’s not good. Fortunately, there’s a method that deals with exactly this sort of thing: chomp. The chomp method takes off any newline characters hanging out at the end of your string. Let’s try that program again, but this time using chomp to help tidy up the response:

​1: puts ​"Hello there, and what's your name?"​ 
​2: name = gets.​chomp​
​3: puts ​"Your name is ​​#{​name​}​​? What a lovely name!"​
​4: puts ​"Pleased to meet you, ​​#{​name​}​​. :)"​
​<= Hello there, and what's your name?
​=> ​Chris​
​<= Your name is Chris? What a lovely name!
​ Pleased to meet you, Chris. :)

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.