0
0
Rubyprogramming~5 mins

String interpolation with #{} in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is string interpolation in Ruby?
String interpolation in Ruby is a way to insert the value of a variable or expression directly into a string using #{ } inside double quotes.
Click to reveal answer
beginner
How do you write a string with a variable inside it using interpolation?
Use double quotes and place the variable inside #{ }. For example: "Hello, #{name}!" will insert the value of the variable name.
Click to reveal answer
intermediate
Why does string interpolation only work with double quotes and not single quotes?
Ruby treats single-quoted strings as plain text and does not process #{ } inside them. Double-quoted strings allow Ruby to evaluate the code inside #{ }.
Click to reveal answer
beginner
Example: What is the output of this Ruby code? name = "Sam"; puts "Hi, #{name}!"
The output will be: Hi, Sam! The #{name} is replaced by the value of the variable name.
Click to reveal answer
intermediate
Can you put any Ruby expression inside #{ } in a string?
Yes! You can put any Ruby code that returns a value inside #{ }, like calculations or method calls, and Ruby will insert the result into the string.
Click to reveal answer
Which of these strings will correctly show the value of variable age using interpolation?
A"I am #{age} years old."
B'I am #{age} years old.'
C"I am $age years old."
D'I am $age years old.'
What will this code print? puts "2 + 3 = #{2 + 3}"
A2 + 3 = #{2 + 3}
B2 + 3 = 2 + 3
C2 + 3 = 5
DError
What happens if you use single quotes with #{ } like '#{name}'?
AIt removes the #{ }
BIt shows the value of name
CIt causes an error
DIt shows the text #{name} literally
Which is true about string interpolation in Ruby?
AIt works only with numbers
BIt only works inside double-quoted strings
CIt only works inside single-quoted strings
DIt works inside both single and double quotes
Can you put method calls inside #{ } in a string?
AYes, Ruby evaluates any expression inside #{ }
BNo, only variables are allowed
COnly numbers are allowed
DOnly strings are allowed
Explain how string interpolation works in Ruby and why double quotes are necessary.
Think about how Ruby treats single vs double quotes.
You got /4 concepts.
    Give an example of using string interpolation with a variable and with a calculation inside the string.
    Try to show both simple and expression interpolation.
    You got /4 concepts.