Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
Ruby provides a feature called string interpolation that lets you substitute the result of Ruby code into the middle of a string.
Ruby provides a feature called string interpolation that lets you substitute the result of Ruby code into the middle of a string.
- Interpolation works within double-quoted Ruby strings.
- Anywhere you want within the string, you can include an interpolation marker. A marker consists of a hash mark (also known as a pound sign), an opening curly brace, and a closing curly brace:
#{}
- You can include any Ruby code you want between the curly braces.
- The code will be evaluated, the result will be converted to a string, and the resulting string will be substituted for the interpolation marker within the containing string.
- Lets us concatenate values like numbers with strings.
- Lets us embed simple math operations.
- Lets us embed the values of variables.
- We can include multiple interpolation markers into a single string.
- No interpolation in single-quoted strings.
$ irb
2.3.0 :001 > "aaa #{Time.now} bbb"
=> "aaa 2017-09-02 19:12:52 -0700 bbb"
2.3.0 :002 > "a string #{1}"
=> "a string 1"
2.3.0 :003 > "The answer is #{1 + 2}"
=> "The answer is 3"
2.3.0 :004 > name = "Jay"
=> "Jay"
2.3.0 :005 > "Hello, #{name}!"
=> "Hello, Jay!"
2.3.0 :006 > "#{Time.now} #{name}"
=> "2017-09-02 19:15:08 -0700 Jay"
2.3.0 :007 > 'Hello, #{name}!'
=> "Hello, \#{name}!"
Widget store code
- Let's try improving our widget store code using string interpolation.
- We'll remove the plus signs to combine all the concatenated strings into one.
- In their place, we'll add an interpolation marker that inserts the value of the
answer
variable:puts "You entered #{answer} widgets"
- It's easy to remember to put spaces surrounding the interpolation marker because it would look funny if we didn't.
def ask(question)
print question + " "
gets
end
puts "Welcome to the widget store!"
answer = ask("How many widgets are you ordering?")
puts "You entered #{answer} widgets"
You can see in the output that it's inserting the value of the answer
variable into the string, and it's surrounded by spaces as it should be.
You entered 10
widgets
It still skips to a new line, which is a problem. We'll have an answer to that shortly.
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up