String Arithmetic

Just as you can do arithmetic on numbers, you can also do arithmetic on strings! Well, sort of…you can add strings, anyway. Let’s try to add two strings and see what puts does with that:

puts ​'I like'​ + ​'apple pie.'
I likeapple pie.

Snap! I forgot to put a space between 'I like' and 'apple pie.'. Spaces don’t usually matter much in your code, but they matter inside strings. (You know what they say: computers don’t do what you want them to do, only what you tell them to do.) Take two:

puts ​'I like '​ + ​'apple pie.'
puts ​'I like'​ + ​' apple pie.'
I like apple pie.
I like apple pie.

(As you can see, it didn’t matter to which string I added the space.)

So, you can add strings, but you can also multiply them! (And I know ...

Get Learn to Program, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.