Chapter 4 Conversions and Input

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Progress Checkpoint | TOC | Numbers to Strings and Back Again 👉

So far, you’ve seen objects like integers, floats, and strings, and you’ve set up variables to point to these objects. Now it’s time for you to get them all to play nicely together.

Let’s suppose you have a program that you want to print 25. Using the following code won’t work because you can’t add numbers and strings together:

​1: var1 =  2 
​2: var2 = ​"5"​
​3: puts var1 + var2

Part of the problem is that Ruby doesn’t know if you were trying to print 7 (2 + 5) or 25 (“2” + “5”), so it’s your job to specify which. But before you can do that, there’s something else you need to do first.

To add the values together in some meaningful way, you first need to convert the objects to be the same type. In other words, you need to get the string version of the integer — in this case var1 — or the integer version of the string — in this case var2.

Let’s look at how you do that.

👈 Progress Checkpoint | TOC | Numbers to Strings and Back Again 👉

Learn to Program, Third Edition by Chris Pine can be purchased in other book formats directly from the Pragmatic Programmers. If you notice a code error or formatting mistake, please let us know here so that we can fix it.

--

--

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.