Strings and Embedded Evaluation

The last line in the sample code is rather interesting:

puts( "Hello #{name}" )

Here the name variable is embedded into the string. You do this by placing the variable between two curly brackets preceded by a hash mark (or “number” or “pound” character), as in #{}. This kind of embedded evaluation works only with strings delimited by double quotes. If you were to try this with a string delimited by single quotes, the variable would not be evaluated, and the string 'Hello #{name}' would be displayed exactly as entered.

You can also embed nonprinting characters such as newlines ("\n") and tabs ("\t"), and you can even embed bits of program code and mathematical expressions. For instance, let’s assume you have a method ...

Get The Book of Ruby 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.