What is String Interpolation in Ruby: Simple Explanation and Example
string interpolation is a way to insert the value of variables or expressions directly inside a string. You do this by placing the code inside #{} within a double-quoted string, and Ruby replaces it with the result when the string runs.How It Works
String interpolation in Ruby works like filling in blanks in a sentence. Imagine you have a sentence with empty spaces, and you want to put names or numbers in those spaces. Instead of building the sentence piece by piece, Ruby lets you write the sentence with placeholders that get replaced automatically.
When Ruby sees #{} inside a double-quoted string, it runs the code inside the braces and puts the result right there in the string. This makes it easy to combine text and values without extra steps.
Example
This example shows how to use string interpolation to include a variable's value inside a string.
name = "Alice" age = 30 message = "Hello, my name is #{name} and I am #{age} years old." puts message
When to Use
Use string interpolation whenever you want to create strings that include changing values like variables or calculations. It is very helpful for making messages, reports, or any text that needs to show dynamic information.
For example, you can use it to greet users by name, show results of math operations, or build sentences that include data from your program.
Key Points
- String interpolation only works inside double-quoted strings or strings with special delimiters.
- The code inside
#{}can be any Ruby expression, like variables, method calls, or calculations. - It makes your code cleaner and easier to read compared to joining strings with plus signs.