rubyguides

Working with strings in Ruby: a complete tutorial

Strings are one of the most frequently used data types in Ruby. Whether you’re building web applications, processing data, or writing scripts, you’ll work with text constantly. This tutorial on working with strings in Ruby covers everything you need to create, mutate, search, and format text effectively.

We open with the four literal forms (single-quoted, double-quoted, heredocs, and percent literals) because the choice you make matters more than people expect: single quotes skip interpolation and most escapes, while double quotes are happy to evaluate #{} expressions and process \n, \t, and the rest. From there we cover the essential methods (length, chars, each_char, gsub, sub, split, strip), the mutating equivalents that end in !, and the small set of conversion helpers like to_s, to_str, and inspect. The final section walks through encodings and force_encoding, which is the most common source of “weird characters in production logs” tickets. For related material, see the Ruby symbols deep dive which contrasts strings with their interned-symbol cousin.

Creating strings

Ruby provides multiple ways to create strings. The most common is using double quotes:

greeting = "Hello, World!"

Single quotes create literal strings—they don’t process escape sequences or interpolation:

literal = 'Hello \\n World'  # => "Hello \\n World"
interpolated = "Hello \\n World"  # => "Hello \n World"

You can also use the %q{} and %Q{} syntaxes, which act like single and double quotes respectively:

single_quoted = %q{Don't worry about escapes}
double_quoted = %Q{You can use #{interpolation} here}

For multi-line strings, use heredocs:

poem = <<~HEREDOC
  Roses are red,
  Violets are blue,
  Ruby is awesome,
  And so are you!
HEREDOC

String interpolation

Interpolation lets you embed variables and expressions inside strings:

name = "Alice"
age = 30

intro = "My name is #{name} and I am #{age} years old."
# => "My name is Alice and I am 30 years old."

calculation = "10 + 5 equals #{10 + 5}"
# => "10 + 5 equals 15"

Only double-quoted strings support interpolation. Ruby evaluates the expression inside #{...} and converts it to a string.

Common string methods

Ruby strings come with powerful built-in methods. Here are the essentials:

Checking string properties

text = "Hello World"

text.length        # => 11
text.empty?        # => false
text.size          # => 11 (same as length)
text.bytesize      # => 11

Case conversion

"Hello".upcase     # => "HELLO"
"HELLO".downcase   # => "hello"
"hello".capitalize # => "Hello"
"HeLLo".swapcase   # => "hEllO"

Searching and substrings

"Hello World".include?("World")  # => true
"Hello World".start_with?("Hello")  # => true
"Hello World".end_with?("!")    # => false

# Finding index of substring
"Hello World".index("World")  # => 6
"Hello World".index("o")     # => 4 (first occurrence)
"Hello World".rindex("o")    # => 7 (last occurrence)

Extracting parts of strings

"Hello World"[0]        # => "H" (first character)
"Hello World"[0..4]     # => "Hello"
"Hello World"[6..10]    # => "World"
"Hello World".slice(0, 5)  # => "Hello"

Modifying strings

Replacing text

greeting = "Hello World"

greeting.gsub("World", "Ruby")  # => "Hello Ruby" (all occurrences)
greeting.sub("World", "Ruby")   # => "Hello Ruby" (first occurrence)

# Using regex
"Hello World".gsub(/[aeiou]/, "*")  # => "H*ll* W*rld"

Stripping whitespace

"  hello  ".strip        # => "hello"
"  hello".lstrip          # => "hello"
"hello  ".rstrip         # => "hello"

# Remove all whitespace
"h e l l o".delete(" ")  # => "hello"

Case comparison

"hello" == "Hello"   # => false (case-sensitive)
"hello".casecmp?("HELLO")  # => true (case-insensitive)

String splitting and joining

Split a string into an array:

"one,two,three".split(",")
# => ["one", "two", "three"]

"Hello World".split(" ")
# => ["Hello", "World"]

"Hello World".chars
# => ["H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d"]

Join array elements into a string:

["Hello", "World"].join(" ")
# => "Hello World"

["a", "b", "c"].join("-")
# => "a-b-c"

Working with numbers and strings

Convert numbers to strings and vice versa:

# Number to string
123.to_s           # => "123"
123.45.to_s        # => "123.45"

# String to number
"123".to_i         # => 123
"123.45".to_f      # => 123.45

# String interpolation handles this automatically
"Value: #{42}"     # => "Value: 42"

Format numbers with specific precision:

"Price: $%.2f" % 99.999  # => "Price: $100.00"

Encoding

Ruby 3+ uses UTF-8 by default. Check and convert encodings:

str = "Hello"
str.encoding        # => #<Encoding:UTF-8>

# Force encoding
str.encode("ASCII")  # => "Hello" (if all ASCII)

# Transcoding
"café".encode("ISO-8859-1")  # Converts to Latin-1

Common pitfalls and tips

New Ruby developers often encounter issues with string immutability. Remember that most string methods return new strings rather than modifying the original. This behavior prevents unexpected side effects in your code.

Another common issue involves special characters. The backslash \ serves as an escape character in double-quoted strings. Use \\ to represent a literal backslash. For Windows paths, remember that backslashes need escaping: "C:\\\\Users\\\\Name".

Performance considerations

For heavy string processing, consider using StringIO for in-memory file-like operations:

require 'stringio'

output = StringIO.new
output.puts "Line 1"
output.puts "Line 2"
output.string  # => "Line 1\nLine 2\n"

Use String#freeze in Ruby 3+ to create immutable string literals, improving memory efficiency in applications that create many identical strings.

When to use strings

Strings are perfect for:

  • User input and output
  • Text processing and parsing
  • File names and paths
  • JSON and XML data
  • Building SQL queries (use parameterized queries instead!)

Avoid strings for:

  • Numeric calculations (use integers/floats)
  • Boolean logic (use true/false)
  • Complex data structures (use hashes/arrays)

Summary

Ruby’s string methods are powerful and expressive. Master these fundamentals:

  • Create strings with quotes or heredocs
  • Use interpolation with double quotes
  • Use built-in methods for common operations
  • Split and join to convert between strings and arrays
  • Remember that strings are immutable—methods return new strings

With these tools, you’ll handle text processing confidently in any Ruby project.