RbRuby · Lesson 6 of 11

Strings & Regex

Ruby's String class has over 100 methods. This is either brilliant or insane, but either way you won't need to import anything.

Ruby
s = "Hello, World!"

# Case
puts s.upcase    # HELLO, WORLD!
puts s.downcase  # hello, world!
puts s.swapcase  # hELLO, wORLD!
puts s.capitalize  # Hello, world!

# Searching
puts s.include?("World")  # true
puts s.start_with?("Hello")  # true
puts s.end_with?("!")     # true
puts s.index("World")     # 7

# Manipulation
puts s.reverse             # !dlroW ,olleH
puts s.length              # 13
puts s.strip               # removes leading/trailing whitespace
puts "  hi  ".lstrip       # "hi  " (left only)
puts s.chomp               # removes trailing newline
puts s.gsub("l", "r")     # Herro, Worrd!
puts s.sub("l", "r")      # Herlo, World! (first only)
puts s.delete("aeiou")    # Hll, Wrld!
puts s.squeeze("l")        # Helo, World!
puts s.tr("aeiou", "*")   # H*ll*, W*rld!

# Splitting / joining
words = "one two three".split       # ["one", "two", "three"]
csv   = "a,b,c,d".split(",")        # ["a", "b", "c", "d"]
puts words.join(" | ")               # one | two | three

# Check and convert
puts "42".match?(/d+/)      # true
puts "hello".chars.inspect   # ["h", "e", "l", "l", "o"]
puts "hello".bytes.first     # 104
Ruby
# String formatting
name = "Alice"
score = 95.5

# String interpolation (preferred)
puts "Name: #{name}, Score: #{score}"

# format / sprintf (C-style)
puts format("%-10s %6.2f", name, score)   # Alice       95.50
puts "Score: %.1f%%" % score              # Score: 95.5%

# Heredoc (multiline string)
text = <<~HEREDOC
  Dear #{name},
  Your score was #{score}.
  Regards, The System
HEREDOC
puts text

# Regex
email = "alice@example.com"
puts email.match?(/A[w+-.]+@[a-zd-.]+.[a-z]+z/i)  # true

phone = "Call us at 555-1234 or 555-5678"
phones = phone.scan(/d{3}-d{4}/)
puts phones.inspect   # ["555-1234", "555-5678"]

# Named captures
if m = "2024-01-15".match(/(?<year>d{4})-(?<month>d{2})-(?<day>d{2})/)
  puts m[:year]   # 2024
  puts m[:month]  # 01
end
✦ Tip
Prefer single-quoted strings when there's no interpolation — `'hello'` instead of `"hello"`. Ruby skips processing escape sequences and interpolation for single-quoted strings, which is marginally faster and signals intent clearly. Use double quotes when you need `#{...}` or `\n`.