ruby variable in string

Ruby Variable in String

To include a Ruby variable in a string, you can use string interpolation. String interpolation allows you to embed the value of a variable directly into a string. Here are the steps to use string interpolation in Ruby:

  1. Define a variable with a value.
  2. Create a string using double quotes (" ").
  3. Inside the string, use the #{} syntax to enclose the variable you want to interpolate.

Here's an example that demonstrates these steps:

name = "John"
age = 25

# Using string interpolation
message = "My name is #{name} and I am #{age} years old."
puts message

Output:

My name is John and I am 25 years old.

In the example above, the variables name and age are interpolated into the string using #{}. The values of the variables are replaced with their actual values when the string is printed.

Please note that string interpolation only works with double-quoted strings (" "), not single-quoted strings (' '). If you use single quotes, the variable will be treated as a literal string and not interpolated.

[[SOURCE 10]]