Strings

6.1 Creating Strings

single = 'No #{interpolation} here\n'      # literal (except \' and \\)
double = "Interpolation: #{1 + 1}\tand escapes\n"
name = "Ana"
greeting = "Hello, #{name}!"
percent_q = %q(single-quoted 'string')
percent_Q = %Q(double-quoted "#{name}")
heredoc = <<~TEXT                          # squiggly heredoc strips leading indentation
  Dear #{name},
    Thanks for joining.
  Regards
TEXT
raw = <<~'RAW'                             # no interpolation
  #{not_interpolated}
RAW
char = ?A                                  # "A"

6.2 Common String Methods

s = "  Hello, Ruby World  "
s.length; s.size
s.strip; s.lstrip; s.rstrip
s.upcase; s.downcase; s.capitalize; s.swapcase
s.include?("Ruby"); s.start_with?("  He"); s.end_with?("  ")
s.index("o"); s.rindex("o")
s.sub("World", "Universe")            # first occurrence
s.gsub("o", "0")                      # all occurrences
s.gsub(/[aeiou]/) { |v| v.upcase }    # with a block
s.split(", "); "a b  c".split          # split on whitespace by default
s.chars; s.bytes; s.lines
s.reverse; s.squeeze; s.count("l")
s.center(30, "*"); s.ljust(30, "."); s.rjust(30)
s.tr("lo", "01"); s.delete("l")
"ruby" * 3                             # "rubyrubyruby"
"a" + "b"; "a" << "b"                  # << mutates (unless frozen)
"hello"[0]; "hello"[-1]; "hello"[1..3]; "hello"[1, 3]
"hello world".slice(0, 5)
"Hello".each_char { |c| print c }
"snake_case_word".split("_").map(&:capitalize).join   # "SnakeCaseWord"
"text".empty?; "  ".strip.empty?
"%05.2f | %-10s | %x" % [3.14159, "left", 255]
format("%s has %d items", "cart", 3)
"abc".succ                             # "abd"
"ruby".encoding                        # UTF-8
"héllo".unicode_normalize; "héllo".bytesize
"Hello" <=> "World"                    # -1
"h
…

6.3 Mutability and Frozen Strings

Ruby 3.4: string literals are "chilled" (they warn when mutated if deprecation warnings are enabled). This prepares for frozen-by-default string literals in a future version.

# frozen_string_literal: true
s = "hello"
s.frozen?             # true (with the magic comment)
s << " world"         # FrozenError
t = +"hello"          # unary plus: unfrozen copy
t << " world"         # OK
u = -"hello"          # unary minus: frozen, deduplicated
s.dup                 # mutable copy

6.4 Encodings

"héllo".encoding                          # #<Encoding:UTF-8>
"héllo".encode("ISO-8859-1")
"bytes".force_encoding("ASCII-8BIT")      # binary
"bad \xFF".valid_encoding?                # false
"bad \xFF".scrub("?")                     # replace invalid bytes