Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 37 ยท Syntax and Types

Strings, Chars and Symbols

Work with Crystal text, from immutable UTF-8 strings, Char literals, symbols, interpolation, heredocs, common string methods and String.build, with read-only code and Ruby stand-ins.

Text in Crystal comes in three flavours: String for sequences of characters, Char for a single character, and Symbol for a fixed name that the compiler knows. Strings are UTF-8, so emoji and non-Latin scripts work without extra effort. This lesson explains each type and the methods you will use daily.

Crystal listings are read-only on this site. Runnable Ruby stand-ins are provided where the Ruby behaviour is the same or where the difference is instructive.

String literals

CRYSTAL
a = "double quotes allow #{1 + 1} interpolation"
b = %q(percent literals: no interpolation here)
c = "line one\nline two"
d = "tab\tseparated"
puts a
puts c

Double-quoted strings support escapes (\n, \t, \", รฉ) and interpolation with #{...}. Crystal has no single-quoted strings: single quotes make a Char, as the next section shows. This is a classic trap for Ruby programmers.

Multi-line text uses a heredoc:

CRYSTAL
text = <<-TEXT
  Dear reader,
    thanks for learning Crystal.
  TEXT
puts text

With <<-TEXT the closing marker may be indented, and the common leading indentation is removed.

Strings are immutable

A String cannot be changed in place. Methods that look like modifications return a new string:

CRYSTAL
s = "crystal"
t = s.upcase
puts s    # crystal
puts t    # CRYSTAL

There is no upcase! on String, and no s[0] = "C". This keeps strings safe to share and cache. To build a string from many pieces, use String.build, which appends into one buffer and is much faster than repeated +:

CRYSTAL
result = String.build do |io|
  3.times { |i| io << "item " << i << "\n" }
end
puts result

This prints three lines: item 0, item 1, item 2. In loops that produce large strings, String.build is the idiom to learn first.

Common methods

CRYSTAL
s = "  Hello, Crystal!  "

puts s.size              # 18
puts s.strip             # "Hello, Crystal!"
puts s.strip.downcase    # "hello, crystal!"
puts s.includes?("Cry")  # true
puts s.starts_with?("  H") # true
puts s.strip.split(", ")   # ["Hello", "Crystal!"]
puts s.strip.sub("Crystal", "World")  # Hello, World!
puts s.strip.reverse     # !latsyrC ,olleH
puts "ab" * 3            # ababab
puts "a,b,c".split(",").join("-")  # a-b-c
puts "crystal".capitalize          # Crystal
puts "x".ljust(3, '.') + "|"       # x..|

size counts characters (UTF-8 code points), while bytesize counts bytes. For "รฉ" they are 1 and 2. Indexing returns a Char, not a string:

CRYSTAL
word = "crystal"
puts word[0]        # c  (a Char)
puts word[0, 3]     # cry (substring by start and length)
puts word[1..3]     # rys (range)
puts word[-1]       # l

If the index is out of range, word[10] raises IndexError, while word[10]? returns nil. The same ? convention appears on many methods.

Here is the Ruby stand-in. These methods behave the same in Ruby, but note that Ruby indexing returns a one-character string, and Ruby strings are mutable:

Ruby Stand-in: string methods in Ruby

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.

Chars

A Char is one Unicode code point written in single quotes.

CRYSTAL
letter = 'a'
puts letter.ord         # 97
puts 98.chr             # b
puts letter.upcase      # A
puts letter.alpha?      # true
puts '7'.to_i           # 7
puts '\n'.ord           # 10
puts 'รฉ'.bytesize       # 2
puts "crystal".chars    # ['c', 'r', 'y', 's', 't', 'a', 'l']

Chars are cheap values (4 bytes), so iterating over them with each_char does not allocate strings. Use Char for a single character, String for anything else, even a one-character string such as "a".

Ruby Stand-in: code points and characters in Ruby

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.

Symbols

A Symbol is a name starting with a colon: :ok, :name. Two uses of the same symbol are always the same value, and symbols are very quick to compare.

CRYSTAL
status = :ready
puts status           # ready
puts status == :ready # true
puts status.to_s      # "ready"

Differences from Ruby that matter:

  • In Crystal, symbols are created at compile time, only from literals. You cannot turn arbitrary text into a symbol at run time with to_sym.
  • They are used less than in Ruby. Crystal prefers enums for a fixed set of choices (see the classes chapter), and NamedTuple or classes for records.
  • Method names and keyword arguments are written with a bare name, so you will not see a lot of symbol options.

Converting and formatting

CRYSTAL
puts 42.to_s                      # "42"
puts "42".to_i + 1                # 43
puts 3.14159.round(2)             # 3.14
puts "%05.1f" % 3.14159           # 003.1
puts "%-6s|" % "ab"               # ab    |
puts 1234567.to_s.reverse.scan(/\d{1,3}/).join(",").reverse  # 1,234,567
puts "Name: %s, age: %d" % ["Ada", 36]

String#% and sprintf use format codes like C: %d integers, %s strings, %f floats, %x hexadecimal.

Comparing and searching

CRYSTAL
puts "apple" < "banana"          # true (lexicographic)
puts "Apple".compare("apple", case_insensitive: true)   # 0
puts "hello world" =~ /wor/      # 6 (index of the match)
puts "a-b_c".tr("-_", "  ")      # a b c
puts "x=1;y=2".scan(/\w=\d/)     # ["x=1", "y=2"]

Equality == compares content. Regular expressions are written between slashes and are built into the language, with matching done by the PCRE2 engine.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does 'a' (single quotes) create in Crystal?

    Single quotes always make a Char. Use double quotes for strings.
  2. 2. Which is true of Crystal strings?

    Strings are immutable UTF-8 values. Use String.build to assemble big strings efficiently.
  3. 3. What does "crystal"[10]? return?

    The ? version of an indexing method returns nil when the index is out of range.
  4. 4. Which is the fastest way to join many pieces into one large string?

    String.build writes into one buffer, avoiding a new string for every step.

Summary

  • String is immutable UTF-8 text in double quotes; Char is one code point in single quotes; Symbol is a compile-time name.
  • Interpolate with #{}, build large text with String.build.
  • Indexing returns a Char; the ? variants return nil instead of raising.
  • size counts characters, bytesize counts bytes.
  • Prefer enums over symbols for fixed choices.

Next: Union Types and nil