- sub
Replace part of a string (substitute)
- If there is nothing to replace, nothing happens
- Only replaces the first occurrence of the string
examples/strings/substitute.cr
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