When Bad Things Happen to Good Programs

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Numbers vs. Digits | TOC | Progress Checkpoint 👉

You’ve seen what happens when you mix strings with numbers and things go right. Now let’s see what happens when things go wrong. Try this:

​1: puts ​"12"​ + 12 
​2: puts ​"2"​ * ​"5"​
​<= example.rb:1:in `+': no implicit conversion of Integer into String (TypeError)
​ from example.rb:1:in `<main>'

Well, that’s not good. You get an error. The problem here is that you can’t add a number to a string or multiply a string by another string. So, for example, you can’t do something like this:

​1: puts ​"Marceline"​ + 12 
​2: puts ​"Finn"​ * ​"Jake"​

When you think about it, adding “Marceline” and 12 makes no sense. Neither does multiplying “Finn” and “Jake”.

Here’s something else to be aware of: you can write “Apollo”*11 in a program, since it means eleven sets of the string “Apollo” all added together. But you can’t write 11*”Apollo”, since that means “Apollo” sets of the number 11, which is certainly creative but will never work.

Here’s another thing that can go wrong: what if you want a program to print out They said, “Yes!” when it runs? You could try this:

​1: puts ​"They said, "​Yes!​""​

--

--

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.