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 you wanted to…you were all like, “But, Chris, can we multiply them?” Yes. Yes, you can.) Watch this:

puts ​'blink '​ * 4

And you get this:

batting her eyes

(Just kidding…not even Ruby is that clever.)

blink blink blink blink

If you think about it, this makes perfect sense. After all, 7*3 really just means 7+7+7, so 'moo'*3 just means 'moo'+'moo'+'moo'.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.167.161