Learning Ruby

Simple Substitution

The String method "sub" allows you to perform a substitution on a string.
You provide it with a regular expression pattern to match the part you want to replace and a string to replace it with.
If the pattern matched it returns the replaced string, if the pattern did not match you get the original string back.


"superman".sub(/man/, 'woman') 
# => superwoman

 

 

January 05, 2010 at 2:57 am