String Methods
Prerequisites: Strings
Strings come with dozens of built-in methods. These are the ones you'll reach for constantly.
Example
text = " Hello, Ruby World "
p text.strip
p text.strip.upcase
p text.strip.downcase
p "ruby".capitalize
p text.include?("Ruby")
p text.strip.start_with?("Hello")
p "a,b,c".split(",")
p "Ruby".reverse
p text.strip.sub("World", "Friends")
p "banana".gsub("a", "o")
p "banana".count("a")
p "Ruby"[0]
p "Ruby"[1..2]
p "".empty?
Expected output
"Hello, Ruby World"
"HELLO, RUBY WORLD"
"hello, ruby world"
"Ruby"
true
true
["a", "b", "c"]
"ybuR"
"Hello, Ruby Friends"
"bonono"
3
"R"
"ub"
true
Things to notice:
- Methods can be chained:
text.strip.upcasestrips first, then upper-cases the result. - Methods ending in
?(include?,empty?) returntrueorfalse. That naming convention is used throughout Ruby. subreplaces the first match;gsub("global substitute") replaces every match.- Square brackets pick characters by position, starting from
0."Ruby"[1..2]takes positions 1 through 2.
Bang methods
Most string methods return a new string and leave the original
alone. Many have a "bang" version ending in ! that changes the
original instead:
word = +"hello"
word.upcase
p word
word.upcase!
p word
"hello"
"HELLO"
The + before "hello" makes an explicitly mutable copy of the
string. Plain string literals still work with bang methods in Ruby 3.4,
but future versions plan to make literals frozen (unchangeable) by
default, so the + keeps this example correct going forward. The
Frozen Objects lesson in Level 2 explains why.
Common mistakes
- Calling
name.upcaseand expectingnameitself to change. Either assign the result (name = name.upcase) or useupcase!.
Practice
Given email = " Ada@Example.COM ", print a cleaned-up version with
no surrounding spaces, all in lowercase.
Show solution
email = " Ada@Example.COM "
puts email.strip.downcase
ada@example.com