Ruby | String Interpolation
Last Updated :
02 Jan, 2023
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
a = 1
b = 4
puts "The number
|
Output :
The number 1 is less than 4
Example:
Ruby
s = 'Groot' ;
n = 16
puts "s age = n";
puts "
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
puts 'guardians\nGroot' ;
puts "guardians\nGroot";
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.
Share your thoughts in the comments
Please Login to comment...