Ruby - String String Substitutions

Introduction

Substitute something within a string for something else.

Demo

puts "foobar".sub('bar', 'foo')

Result

Here, string sub method substitutes the first instance of the first parameter 'bar' with the second parameter 'foo'.

sub method does one substitution at a time on the first instance of the text to match.

String gsub method does multiple substitutions at once:

Demo

puts "this is a test".gsub('i', 'I')

Result