Escape Sequences
Learn about escape sequences.
We'll cover the following
There’s one other little difference between single- and double-quoted strings that we should cover.
Control characters
Strings can contain control characters as well as normal text. Control characters are also called non-printing characters, even though they can have visual effects.
Control characters can represent all sorts of things, such as removing the last character (backspace), the next one (delete), or even causing an auditable alert (bell).
The one most typically used in Ruby programs is the newline character.
Because there’s no way to represent a newline character using any of the keys on our keyboard, programmers have come up with the idea of escape sequences. An escape sequence is code that consists of a backslash and another character. This combination is used in place of control characters. For example, \n
is the escape sequence that stands for the newline character.
Consider this code:
puts "one\ntwo\nthree"
It prints out:
one
two
three
Failure with single-quoted strings
Escape sequences only work in double-quoted strings. What happens if we try to use them in a single-quoted string?
puts 'one\ntwo\nthree'
That prints out the string literally:
one\ntwo\nthree
This means that escape sequences aren’t replaced in single-quoted strings.