Getting Strings from the User

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Let Me Tell You a Secret | TOC | Cleaning Up User Input 👉

To get strings from the user, you use the gets method. If puts means put string, you can probably guess what gets means. And just as puts always spits out strings, gets retrieves only strings. So, where do these strings come from?

From you — well, from your keyboard, anyway! Of course, since your keyboard makes only strings, that works out beautifully. What actually happens is that gets simply sits there, reading what you type until you press Enter. Try it out:

​1: puts gets​=> ​Is there an echo in here?​
​<= Is there an echo in here?

As expected, whatever you type will get repeated back to you. Run it a few times and try typing different things.

Did It Work?

WARNING

Maybe you didn’t need any help installing Ruby, so you skipped Chapter 1. Hey, no problem.

Maybe you’ve done a little programming before, so you skipped Chapter 2. That’s totally fine.

The only thing is that you missed some stuff there that you need to know now. If you haven’t been running your programs from the command line, then you’ll almost certainly have problems with gets, and you’re going to be using it a lot from now on. So, if you saved your program as example.rb…

--

--

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.