Ruby String Template (AKA String Interpolate) Tutorial

In this section, we will learn what the String Template is and how to use it in Ruby.

What is String Template (AKA String Interpolate) in Ruby?

Sometimes we have a variable or a value in a program and want to mix that with a string value in order to create a new string. For example, let’s say your program took the name of a user and now it wants to send a message to the user in order to greet her like “Hello User” where “User” is the name of the person who’s using the program.

This is where we can use the string template to mix in other values into a string value.

The string template basically defines a place within a string value where we can put variables or raw values of any type in there and they will be combined with the string value in order to create a new one.

Let’s see the syntax and an example. Then you’ll see how String Templates work in Ruby.

Ruby String Template Syntax:

“String Value… #{value} another string value...”

The String Template is `#{}`:

  • It starts with a hash tag.
  • Followed by that we have the opening curly brace
  • After that, we put the raw value or the value of a variable we want to mix in with the string value
  • Finally, we close the string template using the closing curly brace.

Note that we use the String template within a string value (that means within a pair of double quotation).

Also, we can use as many string templates as we want in a string value.

Example: using string template in Ruby

full_name = "John Doe"

puts "Hello #{full_name}! Do you like string template? :)"

Output:

Hello John Doe! Do you like string template? 🙂

How does String Template work in Ruby?

In this example, we’ve used one string template in the argument that was passed to the puts method. Here, the value that we’ve set in the string template was the `full_name` variable. So the value of this variable replaced the string template and we got the value of this variable on the output.

Example: substitute string template in Ruby

full_name = "John Doe"

age = 1000

result = "Hello #{full_name}! Your age is: #{age} :)"

puts result

Output:

Hello John Doe! Your age is: 1000 🙂
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies