String character replacements
suggest changeThe tr method returns a copy of a string where the characters of the first argument are replaced by the characters of the second argument.
"string".tr('r', 'l') # => "stling"
To replace only the first occurrence of a pattern, use sub.
"string ring".sub('r', 'l') # => "stling ring"
To replace every occurrence, use gsub.
"string ring".gsub('r','l') # => "stling ling"
An empty replacement deletes the matched characters. tr works on characters, not regular expressions. sub and gsub accept a string or a regexp.
These methods return a new string. tr!, sub!, and gsub! change the receiver. They return nil when nothing changed.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents