TExcelTAD
Home › Ruby › Ruby String Methods

Ruby String Methods

The String class comes with a huge toolbox. You will not memorise all of it — but knowing the most common methods makes everyday text processing short and readable. Remember: methods without ! return a new string and leave the original alone.

Changing case

ruby · try it yourself
s = "hello World"
p s.upcase
p s.downcase
p s.capitalize
p s.swapcase
p "the lord of the rings".split.map(&:capitalize).join(" ")
"HELLO WORLD"
"hello world"
"Hello world"
"HELLO wORLD"
"The Lord Of The Rings"

map(&:capitalize) is shorthand for map { |w| w.capitalize } — you will see this &:method trick often.

Whitespace and padding

ruby · try it yourself
raw = "   pad me   "
p raw.strip
p raw.lstrip
p raw.rstrip
p "line\n".chomp
p "7".rjust(3, "0")
p "Total".ljust(10, ".") + "42"
p "title".center(11, "*")
p "a  b   c".squeeze(" ")
"pad me"
"pad me   "
"   pad me"
"line"
"007"
"Total.....42"
"***title***"
"a b c"

chomp removes a trailing newline — handy when reading lines from a file.

Searching

ruby · try it yourself
email = "maria.lopez@example.org"
p email.include?("@")
p email.start_with?("maria")
p email.end_with?(".com", ".org")
p email.index("@")
p email.count("a")
p email[/@(.+)/, 1]
true
true
true
11
3
"example.org"

end_with? accepts several options and returns true if any matches. email[/regex/, 1] extracts the first capture group of a regular expression (covered in the Regular Expressions lesson).

Replacing

ruby · try it yourself
msg = "I like cats. cats are great."
p msg.sub("cats", "dogs")      # first match only
p msg.gsub("cats", "dogs")     # every match
p msg.gsub(/[aeiou]/, "*")
p msg.delete("aeiou")
p msg.tr("ae", "AE")
p "2025-01-31".tr("-", "/")
"I like dogs. cats are great."
"I like dogs. dogs are great."
"I l*k* c*ts. c*ts *r* gr**t."
"I lk cts. cts r grt."
"I likE cAts. cAts ArE grEAt."
"2025/01/31"

Splitting and joining

ruby · try it yourself
csv = "pen,notebook,,ruler"
parts = csv.split(",")
p parts
p parts.reject(&:empty?).join(" | ")
p "one two  three".split
p "abc".chars
p "line1\nline2".lines
p "hello world".split("", 3)
["pen", "notebook", "", "ruler"]
"pen | notebook | ruler"
["one", "two", "three"]
["a", "b", "c"]
["line1\n", "line2"]
["h", "e", "llo world"]

split with no argument splits on any run of whitespace and ignores leading/trailing spaces.

Inspecting and converting

ruby · try it yourself
w = "Racecar"
p w.length
p w.reverse
p w.downcase == w.downcase.reverse
p w.empty?
p "  ".strip.empty?
p "ab" * 3
p "%.2f" % 3.14159
p "42".to_i + 8
p "Mon,Tue".split(",").map(&:to_sym)
7
"racecaR"
true
false
true
"ababab"
"3.14"
50
[:Mon, :Tue]

Iterating over a string

ruby · try it yourself
"hey".each_char { |c| print c.upcase, " " }
puts
"ab\ncd".each_line { |line| puts "> #{line.chomp}" }
p "banana".each_char.tally
H E Y
> ab
> cd
{"b" => 1, "a" => 3, "n" => 2}

tally counts how many times each element appears and returns a hash.

Quick reference

Method Example Result
length / size "abc".length 3
upcase, downcase, capitalize "ruby".capitalize "Ruby"
strip, chomp " x\n".strip "x"
include?, start_with?, end_with? "abc".include?("b") true
index "abc".index("c") 2
sub, gsub "aa".gsub("a", "b") "bb"
split, chars, lines "a b".split ["a", "b"]
reverse "abc".reverse "cba"
center, ljust, rjust "5".rjust(3, "0") "005"
tr, delete, squeeze "a-b".tr("-", "_") "a_b"

Tip: In irb, "".methods.sort - Object.instance_methods lists only the methods that are special to strings.

Test yourself

What does "a,b,,c".split(",") return?

  1. ["a", "b", "c"]
  2. ["a", "b", "", "c"]
  3. ["a,b,,c"]
  4. ["a", "b", nil, "c"]

What is the difference between sub and gsub?

  1. gsub is faster
  2. sub replaces only the first match, gsub replaces all
  3. sub works only with regular expressions
  4. There is no difference

What does "5".rjust(3, "0") return?

  1. "500"
  2. "005"
  3. "5 "
  4. "0005"