Numbers vs. Digits

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 String Arithmetic | TOC | When Bad Things Happen to Good Programs 👉

12 is a number, but “12” is a string of two digits. To smart human brains, these are similar concepts and we hardly ever talk about them. But to Ruby, these are very different things.

Let’s play around with this for a bit in code to get a feel for how numbers behave differently from strings of digits. Try this:

​1: puts  12  +  12 
​2: puts ​"12"​ + ​"12"​
​3: puts ​"12 + 12"​
​<= 24
​ 1212
​ 12 + 12

And now this:

​1: puts  2  *  5 
​2: puts ​"2"​ * 5
​3: puts ​"2 * 5"​
​<= 10
​ 22222
​ 2 * 5

These examples are pretty clear. But you need to be careful with how you mix your strings and numbers, or you might run into problems.

👈 String Arithmetic | TOC | When Bad Things Happen to Good Programs 👉

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.