Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 134 ยท Getting Started

Strings

Learn Ruby strings - single and double quotes, escapes, interpolation, heredocs, concatenation, mutability, frozen string literals and the chilled string warning.

A string is a sequence of characters: a name, a sentence, a line of a file, a chunk of JSON. Almost every Ruby program builds, cuts, compares and prints strings, so it pays to understand them properly. Ruby strings are friendly (interpolation, heredocs, a huge method library), but they hide one idea that surprises newcomers: strings are mutable objects. Two names can point at the same string, and changing it through one name changes it for both.

This lesson covers how to write strings, how quotes and escapes work, how to build strings from pieces, and how mutability and freezing work, including the warning Ruby prints when you change a plain string literal. The next lesson, String Methods, covers the methods you call on strings.

Writing strings

Ruby has two main quote styles, and the difference matters.

Ruby Single and double quotes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

In single quotes Ruby takes the text almost literally. Only \' and \\ are escapes, and #{...} stays plain text. In double quotes Ruby processes escape sequences (\n newline, \t tab, \" quote, \\ backslash, \u00e9 a Unicode character) and evaluates #{expression} inside the string. Use single quotes for text that has no interpolation if you like, but most Ruby code simply uses double quotes everywhere. Pick one style for your project and let a linter enforce it.

There are alternatives for strings full of quotes. %q(...) behaves like single quotes and %Q(...) (or just %(...)) like double quotes, and you can pick almost any delimiter:

Ruby Percent literals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Notice the last line: two string literals written next to each other are joined at parse time. This is handy for splitting a long literal over several lines.

Interpolation

#{...} accepts any Ruby expression, not only a variable. Ruby calls to_s on the result and inserts it.

Ruby Interpolation calls to_s

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The class at the end shows why to_s matters: define it and your objects drop into strings naturally. The output for nil is an empty string, not the word "nil" (that would be nil.inspect). Interpolation is almost always better than building a string with +, because + refuses to mix types:

Ruby Mixing a string and a number (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Ruby stops with main.rb:2:in 'String#+': no implicit conversion of Integer into String (TypeError). The fix is either age.to_s or, better, "Age: #{age}".

Building strings

There are several ways to join strings, and they are not equal.

Ruby Plus, shovel and concat

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

a + b always creates a new string and leaves both inputs alone. a << b changes a itself and returns it, so calls chain. a += b is shorthand for a = a + b: it creates a new string and rebinds a. This is the same mutation-versus-rebinding distinction from Variables and Constants.

When you build a big string in a loop, prefer << (one growing buffer) or collect pieces in an array and call join at the end. Repeated += copies the whole string every time, which makes the loop slower than it needs to be.

Heredocs

A heredoc is a multi-line string. Use <<~ (the "squiggly" form): it removes the common leading indentation, so your code can stay indented.

Ruby Squiggly heredocs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The word after <<~ (any identifier, by convention uppercase) marks where the text ends: a line containing only that word. The heredoc behaves like a double-quoted string. Put the terminator in single quotes (<<~'RAW') and it behaves like a single-quoted string. You can call methods straight after the opening tag, as in <<~ONE.upcase, and even start two heredocs on one line; their bodies follow in order. The older <<- form keeps the body's indentation exactly as written (it only lets you indent the terminator), and plain << requires the terminator at the very start of its line, so <<~ is the one to learn.

Strings are mutable

Many Ruby methods come in two versions: upcase returns a new string, upcase! changes the original. The bang (!) versions mutate.

Ruby Two names, one string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

== asks "same characters?", equal? asks "same object?". Almost always you want ==. Because two names can share one string, a method that receives a string and calls << or a bang method on it will change the caller's string. Defensive code either avoids bang methods on arguments or calls dup first. See Copying Objects for the details.

Frozen strings and the chilled string warning

A frozen object refuses to change. Calling freeze on a string makes any mutation raise FrozenError:

Ruby Changing a frozen string (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The output is true and then the error main.rb:3:in '<main>': can't modify frozen String: "ruby" (FrozenError).

Frozen strings are useful: they are safe to share, can be reused instead of copied, and they make a constant truly constant. That is why Ruby has been moving toward frozen string literals. Historically a plain "text" literal was mutable, and a magic comment at the top of a file switched on freezing for that file:

Ruby
# frozen_string_literal: true

NAME = "ruby"
NAME << "ist"   # raises FrozenError

That comment is extremely common in real code bases, and it is a good default in your own files. Without the comment, Ruby uses an in-between state called a chilled string. A plain literal is not frozen, so mutating it works, but Ruby prints a warning to tell you that a future version will refuse:

Ruby The chilled string warning

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Deprecation warnings are switched off in a default run, so the first line of the example turns them on (the same thing ruby -w or ruby -W:deprecated does). On Ruby 4.0.9 the runner then prints main.rb:6: warning: literal string will be frozen in the future (run with --debug-frozen-string-literal for more information) for the mutation. frozen? still answers false, so the code behaves as before. Two small operators control this explicitly: +"text" returns an unfrozen string (a copy if the original was frozen or chilled), and -"text" returns a frozen, de-duplicated one.

Treat the chilled-string warning as a to-do item. Either add # frozen_string_literal: true to the file and fix the places that mutate, or write +"" or String.new where you really need a mutable buffer. Interpolated strings ("a#{x}") are never frozen or chilled, only plain literals are.

Encoding in one paragraph

Ruby strings carry an encoding, and source files are UTF-8 by default. "รฉ".length counts characters (1), while "รฉ".bytesize counts bytes (2). Most of the time you do not think about it. It matters when you read binary data or text from legacy systems; the next lesson shows encoding, force_encoding and valid_encoding?.

Ruby Characters versus bytes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Comparing strings

Comparison is by characters, left to right, using code point order. That means uppercase letters sort before lowercase letters, which can surprise you.

Ruby Comparing and sorting strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

<=> returns -1, 0 or 1 (or nil if the values cannot be compared), and Comparable builds <, > and between? on top of it. Use casecmp? or downcase when you want a case-insensitive comparison, and sort_by(&:downcase) to sort naturally.

Pitfalls and good habits

  • Use == for content, not equal?.
  • Do not modify strings you were handed. Return a new string, or dup first.
  • Prefer interpolation to + when mixing types, and << or join in loops.
  • Single quotes do not interpolate: '#{x}' is literally those characters.
  • A heredoc terminator must sit alone on its line (with <<~ it may be indented).
  • When you need a mutable string from a literal, write +"..." or String.new.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does puts 'Total: #{1 + 1}' print?

    Single-quoted strings do not interpolate. The text is printed exactly as written. Use double quotes to evaluate the expression.
  2. 2. After a = 'hi'; b = a; a << '!', what is b?

    b and a name the same string object, and << changes that object in place, so both names see "hi!".
  3. 3. Which line raises a TypeError?

    String#+ does not convert an Integer implicitly, so it raises no implicit conversion of Integer into String. (<< with an Integer appends the character with that code, which is a different quirk.)
  4. 4. What does <<~ do in a heredoc?

    The squiggly heredoc strips the smallest shared indentation so the body can be indented with your code. Interpolation is turned off by quoting the terminator, not by the tilde.
  5. 5. What does +"text" return?

    Unary plus gives you a string you can safely mutate. Unary minus does the opposite and returns a frozen, de-duplicated string.

Summary

  • Single quotes are literal (only \' and \\), double quotes process escapes and #{...} interpolation.
  • %q()/%Q() and heredocs (<<~) help with quotes and multi-line text.
  • + builds a new string, << appends in place, += rebinds; use join or << in loops.
  • Strings are mutable and shared by reference; use dup, freeze and == versus equal? consciously.
  • A plain literal is "chilled" in Ruby 4.0: mutation works, and warns once deprecation warnings are switched on. Use # frozen_string_literal: true, +"" or String.new.
  • Length counts characters, bytesize counts bytes; comparison uses <=> and code point order.

Next: String Methods