String character replacements

suggest change

The 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents