Strings
Prerequisites: Data types
A string is a piece of text: a sequence of characters in quotes.
Syntax
single = 'Hello'
double = "Hello"
The difference between the two kinds of quotes matters:
- Double quotes support interpolation —
#{...}inside the string runs the Ruby code between the braces and inserts the result — and escape sequences such as\n(new line) and\t(tab). - Single quotes take the text literally;
#{...}and\nare left as-is.
Example
name = "Ada"
age = 36
puts "Hello, #{name}!"
puts 'Hello, #{name}!'
puts "Next year you'll be #{age + 1}."
puts "Line one\nLine two"
puts "Hello, " + name
puts "ha" * 3
puts name.length
Expected output
Hello, Ada!
Hello, #{name}!
Next year you'll be 37.
Line one
Line two
Hello, Ada
hahaha
3
Interpolation is the idiomatic way to build strings in Ruby. It also
converts values for you — "#{age}" works even though age is a
number, whereas "Age: " + age raises a TypeError.
Multi-line strings
A heredoc holds several lines of text. The ~ strips the
indentation:
name = "Ada"
message = <<~TEXT
Dear #{name},
Thanks for signing up.
TEXT
puts message
Dear Ada,
Thanks for signing up.
Common mistakes
- Using single quotes and wondering why
#{name}wasn't replaced. - Joining a string and a number with
+. Use interpolation instead.
Practice
Store a product name and a price in two variables, then print
Coffee costs $3.5 using interpolation.
Show solution
product = "Coffee"
price = 3.5
puts "#{product} costs $#{price}"