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 (" ") and tabs (" "), and you can even embed bits of program code and mathematical expressions. For instance, let’s assume you have a method called showname that returns the string “Fred.” The following string would, in the process of evaluation, call the showname method and display “Hello Fred”:

puts "Hello #{showname}"

See whether you can figure out what would be displayed by the following:

3string_eval.rb

puts( "
	#{(1 + 2) * 3}
Goodbye" )

Now run the 3string_eval.rb program to see whether you are right.

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

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