Introduction
Ruby is a general-purpose, dynamic, reflective, object-oriented programming language. Everything in Ruby is an object. Ruby's development aimed to create a user interface between human programmers and the underlying computational machinery.
The string data type is the most common data type found in all the programming languages.
A string is a collection of one or more characters, which might be letters, numbers, or symbols. In contrast to other programming languages, Ruby's strings are objects that may be modified in-place rather than replaced entirely.
Let’s learn about String Interpolation in Ruby.
String Interpolation
String interpolation is the process of replacing specified variables or expressions in a given String with acceptable values. It is all about concatenating strings together but not using the + operator.
String interpolation only functions when the string creation is done using double quotes (" "). String literals may be processed simply using String Interpolation.
Syntax:
#{variable}
The above syntax indicates that the elements inside the curly braces { } are variables or executable objects.
Let’s understand this with the help of an example.
Example1:
name = "Ninjas"
designation1 = "Developers"
designation2 = "Data Scientists"
#string interpolation
puts "#{name} are #{designation1} and #{designation2}."
Output:
Ninjas are Developers and Data Scientists.
In the above example, we see that the variables name, desigantion1, and designation2 are easily interpolated in the string using string interpolation.
Example2:
var1 = 10
var2 = 20
#string interpolation
puts "var1 is greater than var2: #{var1>var2}."
puts "var1 is less than var2: #{var1<var2}."
Output:
var1 is greater than var2: false.
var1 is less than var2: true.
In the above example, we see that we can also perform any type of operations on variables inside the curly braces { }. Since the var1 is less than var2, it gives false in the case of var1>var2 and true in the case of var1<var2.