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 with with another expression use the sub method

"string ring".sub('r', 'l') # => "stling ring"

If you would like to replace all occurrences of a pattern with that expression use gsub

"string ring".gsub('r','l') # => "stling ling"

To delete characters, pass in an empty string for the second parameter

You can also use regular expressions in all these methods.

It’s important to note that these methods will only return a new copy of a string and won’t modify the string in place. To do that, you need to use the tr!, sub! and gsub! methods respectively.

Feedback about page:

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



Table Of Contents