Ruby Strings

String Basics

Creation and interpolation
single = 'no interpolation here'
double = "port #{port} is open"
heredoc = <<~CONFIG
  server {
    listen 443;
    server_name #{host};
  }
CONFIG

# Frozen strings (immutable)
name = "evan".freeze
# name << " m"             # FrozenError
# Magic comment: # frozen_string_literal: true

String Methods

Searching and testing
hostname = "sw-core-01.inside.domusdigitalis.dev"

hostname.include?("core")         # => true
hostname.start_with?("sw-")      # => true
hostname.end_with?(".dev")        # => true
hostname.length                   # => 42
hostname.count(".")               # => 3
hostname.index("core")            # => 3
Transformations
name = "evan modestus"
name.upcase                       # => "EVAN MODESTUS"
name.capitalize                   # => "Evan modestus"
name.reverse                      # => "sutsedom nave"

"  hello  ".strip                 # => "hello"

hostname.sub("core", "access")    # first occurrence
hostname.gsub(".", "_")           # all occurrences
hostname.delete(".")              # remove all dots
hostname.tr("a-z", "A-Z")        # transliterate

Splitting and Joining

Split, join, and slicing
fqdn = "vault-01.inside.domusdigitalis.dev"

parts = fqdn.split(".")          # => ["vault-01", "inside", ...]
host, *domain = fqdn.split(".")  # destructure

["10", "50", "1", "40"].join(".") # => "10.50.1.40"

fqdn[0..7]                       # => "vault-01"
fqdn[-3..]                       # => "dev"
fqdn.partition(".")              # => ["vault-01", ".", "inside..."]

# Scan -- extract all matches
"port 22, port 443, port 8080".scan(/\d+/)  # => ["22", "443", "8080"]

Regular Expressions

Regex with strings
log = '2026-04-10 14:30:22 ERROR auth failed from 10.50.1.99'

log =~ /ERROR/                    # => 20 (index)
log =~ /WARNING/                  # => nil

# Captures
if log =~ /(\d+\.\d+\.\d+\.\d+)/
  puts "IP: #{$1}"               # => "IP: 10.50.1.99"
end

# Named captures
if log.match(/(?<ip>\d+\.\d+\.\d+\.\d+)/)
  puts $~[:ip]
end

# gsub with regex
log.gsub(/\d+\.\d+\.\d+\.\d+/, "<REDACTED>")

Encoding and Conversion

Type conversion
"443".to_i                        # => 443
"3.14".to_f                       # => 3.14
"hello".to_sym                    # => :hello
443.to_s(16)                      # => "1bb" (hex)
443.to_s(2)                       # => "110111011" (binary)

# Formatting
"%-20s %5d" % ["hostname", 443]