String Interpolation
This lesson explains string interpolation, their usage in strings and "escape sequences".
As mentioned above you can stick strings together by using the +
operator.
Consider the following code:
name = "Ada"puts "Hello, " + name + "!"
This, of course, will output the message Hello, Ada!
.
Glueing strings together like this works, and you can do it. However, there is
another method of accomplishing the same, and it is widely used, and usually
preferred over concatenating strings with +
.
This method is called “string interpolation”, and this is how it looks:
name = "Ada"puts "Hello, #{name}!"
Using this syntax everything between the opening #{
and closing }
bits is
evaluated as Ruby code, and the result of this evaluation will be embedded
into the string surrounding it.
Strings and String Interpolation
In other words, when Ruby finds #{name}
in this string, then it will
evaluate the piece of Ruby code name
. It finds that this is a variable, so it
returns the value of the variable, which is the string "Ada"
. So it embeds it
into ...
Create a free account to access the full course.
By signing up, you agree to Educative's Terms of Service and Privacy Policy