Ruby - Strings and Embedded Evaluation

Introduction

Consider the following code.

Demo

print( 'Enter your name: ' ) 
name = gets() 
puts( "Hello #{name}" )

Result

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, as in #{}.

This kind of embedded evaluation works only with strings delimited by double quotes.

You can embed nonprinting characters such as newlines \n and tabs \t.

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}" 

The following code uses math expression in embedded evaluation:

Demo

puts( "\n\t#{(1 + 2) * 3}\nGoodbye" )

Result

Related Topic