Computer Science Canada

[Ruby-tut] Easily creating strings

Author:  wtd [ Sat Nov 13, 2004 1:05 am ]
Post subject:  [Ruby-tut] Easily creating strings

In Ruby, we cannot simply add a number to a string and expect it to magically work. Something like:

code:
"hello " + 42


Simply doesn't work. We can explicitly turn 42 into a string, though, and then it will.

code:
"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.

code:
"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:

code:
"Hello, #{if true then "Mike" else "John" end}!"


The result of course is:

code:
"Hello, Mike!"


: