Patterns in slashes: find where text fits with =~, harvest every match with scan, and rewrite strings with sub and gsub.
The big picture
A pattern language inside the language
A regex like /c.t/ is a tiny search recipe: Ruby slides it across a string and reports every place it fits.
1
Regexes Are Literal
Write patterns between slashes: /cat/, /\d+/, /^hi/ — they are Regex objects.
2
=~ Finds the Spot
text =~ /pattern/ returns the index of the first match, or nil when nothing fits.
3
scan Collects All
text.scan(/pattern/) gathers every match into an array.
4
sub and gsub Rewrite
sub replaces the first match; gsub replaces every one of them.
A pattern language inside the language
Regexes Are Literal1Write patterns between slashes: /cat/, /\d+/, /^hi/ — they are Regex objects.
=~ Finds the Spot2text =~ /pattern/ returns the index of the first match, or nil when nothing fits.
scan Collects All3text.scan(/pattern/) gathers every match into an array.
sub and gsub Rewrite4sub replaces the first match; gsub replaces every one of them.
4 building blocks make up A pattern language inside the language
Visualize
How the engine finds a match
The pattern slides across the string one position at a time until it fits — or the string ends.
process decision input / output start / end
Watch it run
One pattern, four tools
The dot in /c.t/ matches any single character — watch each tool report differently.
regex.rb
1text ="cat, cot, cut"
2
3puts text =~/cot/
4puts text.scan(/c.t/)
5puts text.match(/c.t/)[0]
6puts text.sub(/c.t/,"dog")
main
text holds three c-t words separated by commas.
Memory
text= cat, cot, cut
Console
output appears as the program runs…
Step 1/6
In 3D
The array scan builds
scan collects its matches into a new array, one fit per cell. Play the script, then drag to orbit.
Drag to orbit the scene. Press Play to watch memory in action.
Challenge
Predict the output
mississippi versus four different pattern tools.
mississippi.rb
1word ="mississippi"
2
3puts word.scan(/ss/).length
4puts word =~/iss/
5puts word.gsub(/ss/,"S")
6puts word.sub(/s/,"T")
Your predicted output — one line per console line
Hint: scan(/ss/) finds two non-overlapping "ss" pairs. =~ reports the starting index of "iss" (1). gsub swaps every match while sub swaps only the first single s.
Recap
Key takeaways
Key takeaways5 takeaways
01
A regex like /c.t/ is a pattern: the dot matches any single character.
02
=~ returns the match index, or nil when nothing fits.
03
match gives you a MatchData object; scan collects every match into an array.
04
sub replaces the first match; gsub replaces them all.
05
Escapes like \d, \w and \s match digits, word characters and whitespace.