Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Replace part of a string (substitute)

  • sub

  • If there is nothing to replace, nothing happens

  • Only replaces the first occurrence of the string

text = "The black cat climbed the green tree"

new_text = text.sub("cat", "dog")
puts text
puts new_text

new_text = text.sub("dog", "elephant")
puts text
puts new_text

text = "Red cat, Blue cat"
new_text = text.sub("cat", "dog")
puts text
puts new_text

animal = "cat"
new_text = text.sub animal do |original|
  original.upcase
end
puts new_text
The black cat climbed the green tree
The black dog climbed the green tree
The black cat climbed the green tree
The black cat climbed the green tree
Red cat, Blue cat
Red dog, Blue cat
Red CAT, Blue cat