String Arithmetic

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Chapter 2 Letters | TOC | Numbers vs. Digits 👉

Just as you can do arithmetic on numbers, you can also do arithmetic on strings. Well, sort of. You can add strings together.

Let’s try to add two strings and see how puts handles that:

​1: puts ​"I like"​ + ​"apple pie."​​<= I likeapple pie.

Whoops! There’s no space between “I like” and “apple pie.”. Spaces don’t usually matter much in your code, but inside a string they matter a lot. (You know what they say: computers don’t do what you want them to do, only what you tell them to do.)

Okay, let’s try this again:

​1: puts ​"I like "​ + ​"apple pie."​ 
​2: puts ​"I like"​ + ​" apple pie."​
​<= I like apple pie.
​ I like apple pie.

Ah, much better. For the record, you can add the space to either string.

Adding strings is cool, but you can do more than that: you can also multiply them. Watch this:

​1: puts ​"blink "​ * 4

And you get this:

​<= batting my eyes

Just kidding. Not even Ruby is that clever. What you actually get is this:

​<= blink blink blink blink

--

--

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.