Ruby Language Strings String character replacements

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

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.



Got any Ruby Language Question?