Open In App

Ruby | String Interpolation

Improve
Improve
Like Article
Like
Save
Share
Report

String Interpolation, it is all about combining strings together, but not by using the + operator. String Interpolation works only when we use double quotes (“”) for the string formation. String Interpolation provides an easy way to process String literals. String Interpolation refers to substitution of defined variables or expressions in a given String with respected values. This is how, string Interpolation works, it executes whatever that is executable. Let’s see how to execute numbers and strings. Syntax:

#{variable}

The above syntax specifies that the things inside {} are executable objects or variables. Below are the examples to understand : Example : 

Ruby




# Ruby Program of String Interpolation
a = 1
b = 4
puts "The number #{a} is less than #{b}"


Output :

The number 1 is less than 4

Example: 

Ruby




# Ruby Program of String Interpolation
 
s = 'Groot';
n = 16
 
# takes this as entire new string
puts "s age = n";
 
# interpolation
puts "#{s} age=#{n}";
 
# if number not converted to string throws an error
puts s+" age="+n.to_s;


Output:

s age=n
Groot age=16
Groot age=16

So, the only advantage, We don’t have to convert numbers into a string because ruby takes care of it. let’s say string=”weds” In string concatenation, if we are concatenating strings like (“hela “+string+” puri”), it creates 3 string objects, it moves from right-to-left, it first creates ” puri” object1, + method sticks the puri with the existing string together and returns weds puri object2 and this again gets stick by + method and forms the final hela weds puri object3. Eventually, the objects(1, 2) created in this process gets terminated as they are of no use. In String Interpolation, it creates an only one object for (“hela “+string+” puri”) and embeds the existing string(weds)to it. In both the case, in the end, it creates one object but why prefer Interpolation over concatenation. Two reasons, no need for additional conversions of datatypes to string ruby takes care of it and this process is most of the developers kinda use.

Escape sequences

Strings can not only contain text. They can also contain control characters. Difference between single or double quotes is that double quotes allow for escape sequences while single quotes do not allow for it. Example : 

Ruby




# Ruby program of string Interpolation
puts 'guardians\nGroot';
 
# gets executes and prints Groot on a newline.
puts "guardians\nGroot";
 
# takes care of control characters.
puts "hela\nweds\tpuri";


Output:

guardians\nGroot
guardians
Groot
hela
weds    puri

In above example, \n is the escape sequence that stands for the “newline” character.



Last Updated : 02 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads