
-----------------------------------
wtd
Sat Nov 13, 2004 1:05 am

[Ruby-tut] Easily creating strings
-----------------------------------
In Ruby, we cannot simply add a number to a string and expect it to magically work.  Something like:

"hello " + 42

Simply doesn't work.  We can explicitly turn 42 into a string, though, and then it will.

"hello " + 42.to_s

But that takes a fair amount of work, and it just isn't natural.  

So, we either need to make the first example work, or we need a better way to construct strings.

Don't hold your breath waiting for the latter.  There are good reasons it won't work.  However we do have a better way to construct strings.

"hello #{42}"

This is known as string interpolation.  Whatever is in the #{ } brackets is inserted into the string with an implied call to to_s.  

Whatever you include?  So... anything could be put in their?

Yep.  Consider something like:

"Hello, #{if true then "Mike" else "John" end}!"

The result of course is:

"Hello, Mike!"
