Ruby - String String Interpolation

Introduction

Consider the following code:

Demo

x = 10 
y = 20 
puts "#{x} + #{y} = #{x + y}"

Result

You can embed expressions and logic directly into strings.

This process is called interpolation.

String interpolation can insert the result of an expression into a string literal.

To interpolate within a string, place the expression within #{ and } symbols.

Demo

puts "100 * 5 = #{100 * 5}"

Result

The #{100 * 5} section interpolates the result of 100 * 5 into the string at that position.

You can interpolate other strings, too:

Demo

x = "cat" 
puts "The #{x} in the hat" 

puts "It's a #{"nice " * 2}world"

Result

Interpolation works within strings used in assignments:

Demo

my_string = "It's a #{"nice " * 3}world" 
puts my_string

Result

Related Topics