String Interpolation
String interpolation lets you drop a value right inside a sentence, like filling in a blank in a story. Ruby swaps the marker for the actual value.
In this page:
Syntax
name = "value"
puts "text #{name} more text"
puts "sum: #{expression}"
String Interpolation
Ruby lets you embed expressions directly inside a double-quoted string with #{expression}, which evaluates the expression and inserts its string form.
This only works in double-quoted strings, not single-quoted ones. Interpolation is the idiomatic Ruby way to build strings, generally preferred over concatenation with +.
Warning:
String interpolation only works inside double quotes -- 'Hello #{name}' with single quotes prints the literal text, not the interpolated value.
Example: String Interpolation
name = "Ruby"
version = 3.2
puts "Hello, #{name}! Version: #{version}"
puts "2 + 2 = #{2 + 2}"
puts 'No interpolation here: #{name}'
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using single quotes as in
'Hello, #{name}', which prints#{name}literally. - Forgetting the braces, such as
"Hello #name", which prints#name. - Concatenating a number with
+such as"Total: " + 5, which raisesTypeError; interpolate with#{5}.
Chapter Summary
- Ruby is a language you can run with IRB or as scripts after installing it.
puts,print, andpdisplay output, and comments document code.- String interpolation inserts values into text.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: