How to Work with Strings in Ruby
Ruby strings are incredibly versatile objects. Whether you’re cleaning user input, parsing file contents, or building dynamic URLs, you’ll constantly work with text. This cookbook gives you practical recipes for common string operations.
Trimming Whitespace
White space at the edges of strings often comes from user input or file processing. Ruby gives you several methods to handle it.
Basic Trimming
The strip method removes leading and trailing whitespace:
name = " John Doe "
name.strip # => "John Doe"
Use lstrip to remove only leading whitespace, and rstrip for trailing:
" hello".lstrip # => "hello"
"hello ".rstrip # => "hello"
These methods return new strings. Use the bang versions (strip!, etc.) to modify in place.
Removing Specific Characters
The chomp method removes trailing newlines or a specified suffix:
"hello\n".chomp # => "hello"
"hello\r\n".chomp # => "hello"
"hello.".chomp(".") # => "hello"
The chop method removes the last character regardless of what it is:
"hello!".chop # => "hello"
Case Conversion
Converting string case is essential for normalization and display.
Uppercase and Lowercase
"hello".upcase # => "HELLO"
"HELLO".downcase # => "hello"
Capitalize and Swap
The capitalize method makes the first character uppercase and the rest lowercase:
"hello WORLD".capitalize # => "Hello world"
The swapcase method swaps uppercase to lowercase and vice versa:
"Hello World".swapcase # => "hELLO wORLD"
Searching and Replacing
Checking for Substrings
Use include? to check if a string contains a substring:
"hello world".include?("world") # => true
"hello".include?("xyz") # => false
Simple Replacement with sub and gsub
The sub method replaces the first occurrence:
"hello world".sub("world", "ruby") # => "hello ruby"
The gsub method replaces all occurrences:
"one one one".gsub("one", "1") # => "1 1 1"
Both methods support regex:
"hello 123 world".gsub(/\d+/, "NUM") # => "hello NUM world"
Pattern Matching
The match method returns a MatchData object:
result = "price: $49.99".match(/\$\d+\.\d+/)
result[0] # => "$49.99"
For simple checks, use =~ (returns index) or match? (returns boolean):
"hello" =~ /ell/ # => 1
"hello".match?(/xyz/) # => false
Splitting and Joining
Splitting Strings
The split method breaks a string into an array:
"one,two,three".split(",") # => ["one", "two", "three"]
Split on whitespace automatically:
"hello world".split # => ["hello", "world"]
Limit the number of splits with the second argument:
"a,b,c,d".split(",", 2) # => ["a", "b,c,d"]
Character and Line Splitting
The chars method returns an array of characters:
"hello".chars # => ["h", "e", "l", "l", "o"]
The lines method splits on newlines:
"line1\nline2\nline3".lines # => ["line1\n", "line2\n", "line3"]
Joining Arrays
The inverse of split is join:
["a", "b", "c"].join("-") # => "a-b-c"
["hello", "world"].join(" ") # => "hello world"
String Interpolation
Basic Interpolation
Ruby string interpolation evaluates expressions inside #{}:
name = "Alice"
"Hello, #{name}!" # => "Hello, Alice!"
Alternative Delimiters
For strings containing many quotes, use alternative delimiters:
%Q(He said: "Hello") # Double-quoted
%q(He said: 'Hello') # Single-quoted (no interpolation)
The %w shortcut creates word arrays:
%w[apple banana cherry] # => ["apple", "banana", "cherry"]
Encoding Considerations
Ruby 3+ handles encoding carefully. Most strings default to UTF-8.
Checking Encoding
"hello".encoding # => #<Encoding:UTF-8>
Force Encoding
If you have encoding issues, force it:
str = "\xC3\xA9".force_encoding("UTF-8")
Valid Encoding
Check if a string is valid UTF-8:
"hello".valid_encoding? # => true
Practical Examples
Slugifying a String
Create URL-friendly slugs:
def slugify(text)
text.downcase
.strip
.gsub(/[^\w\s-]/, "")
.gsub(/\s+/, "-")
end
slugify("Hello World!") # => "hello-world"
Truncating Text
Add ellipsis to long strings:
def truncate(text, length = 100)
return text if text.length <= length
text[0...length].strip + "..."
end
truncate("This is a long string...", 10) # => "This is a..."
See Also
- string::include? — Check if a string contains a substring
- Working with Arrays in Ruby — Companion guide for array operations