๐ŸŽ“ A1Learner
๐Ÿ”
0 of 34 lessons completed

Ruby Working with Strings

Strings can change in place as well as make new copies. This lesson appends to one string, replaces text inside it, and rewrites single letters.

Appending with <<

The << operator adds text to the end of the same string. The string grows instead of a new string being built.

word = "cat"
word << "s"
puts word
word << "!"
puts word

Replacing every match with gsub

gsub looks for a plain string pattern. Every match in the text is swapped for the replacement.

text = "one fish, two fish"
puts text.gsub("fish", "bird")

Replacing the first match with sub

sub works like gsub but stops after one swap. Later matches stay as they were.

text = "one fish, two fish"
puts text.sub("fish", "bird")

Swapping one letter in place

Assigning to a slice changes the string itself. The letter at position 0 is replaced by the new letter.

word = "cat"
word[0] = "b"
puts word

Walking letters with each_char

each_char hands the block one letter at a time. The letters are gathered here into an array.

letters = []
"ruby".each_char do |letter|
  letters << letter
end
p letters

Example

message = "red pen, red ink"
message = message.gsub("red", "blue")
puts message
message[0] = "B"
puts message

Key points

  • The << operator appends text to the same string.
  • gsub replaces every match of a plain string pattern.
  • sub replaces only the first match.
  • Slice assignment replaces the letters at a position inside the string.
  • each_char walks a string one letter at a time.

In this example, gsub swaps both copies of red for blue and the result is stored back in message. Slice assignment then replaces the first letter with a capital B. Each print shows the string after one change.

Note

The patterns in this lesson are plain strings, matched letter for letter.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does the code puts "aa".sub("a", "b") print?