- Comprehensive Ruby Programming
- Jordan Hudgens
- 316字
- 2021-07-02 21:13:26
What is string interpolation?
So what exactly is string interpolation? Good question. String interpolation is the process of being able to seamlessly integrate dynamic values into a string.
Let's assume we want to slip dynamic words into a string. We can get the input from the console and store that input into variables. From there, we can call the variables inside of a pre-existing string.
For example, let's give a sentence the ability to change based on a user's input:
puts "Name an animal"
animal = gets.chomp
puts "Name a noun"
noun= gets.chomp
p "The quick brown #{animal} jumped over the lazy #{noun}"
Note the way I insert variables inside the string. They are enclosed in curly brackets and are preceded by a # sign.
If I run this code, this is what my output will look like:

So, this is how you insert values dynamically in your sentences.
If you see sites such as Twitter, it sometimes displays personalized messages such as: Good morning Jordan or Good evening Tiffany. This type of behavior is made possible by inserting a dynamic value in a fixed part of a string, and it leverages string interpolation.
Now, let's use single quotes instead of double quotes, to see what happens:

As you'll see, the string was printed as it is, without inserting the values for animal and noun. This is exactly what happens when you try using single quotes—it prints the entire string as it is without any interpolation. Therefore, it's important to remember the difference.
Another interesting aspect is that anything inside the curly brackets can be a Ruby script. So, technically you can type your entire algorithm inside these curly brackets, and Ruby will run it perfectly for you. However, this is not recommended for practical programming purposes.
For example, I can insert a math equation, and as you'll see it prints the value out:

- Unreal Engine Physics Essentials
- 機(jī)器學(xué)習(xí)系統(tǒng):設(shè)計(jì)和實(shí)現(xiàn)
- 深度學(xué)習(xí):算法入門與Keras編程實(shí)踐
- 一本書講透Java線程:原理與實(shí)踐
- Emgu CV Essentials
- Java Web從入門到精通(第3版)
- 零基礎(chǔ)學(xué)C++(升級(jí)版)
- Redmine Cookbook
- ROS機(jī)器人編程實(shí)戰(zhàn)
- 3ds Max 2018從入門到精通
- Java Web應(yīng)用開發(fā)
- JavaScript編程精解(原書第3版)
- Elasticsearch實(shí)戰(zhàn)(第2版)
- 三步學(xué)Python
- Java EE框架開發(fā)技術(shù)與案例教程