Text Processing
Gsub Scan
gsub replaces matching text, while scan collects matches.
Gsub Scan
gsub_scan.rb
word =
text = "red blue red"
pattern = Regexp.new(word)
matches = text.scan(pattern)
replaced = text.gsub(pattern, "item")
puts "word=#{word}"
puts "matches=#{matches.length}"
puts "replaced=#{replaced}"
word =
text = "red blue red"
pattern = Regexp.new(word)
matches = text.scan(pattern)
replaced = text.gsub(pattern, "item")
puts "word=#{word}"
puts "matches=#{matches.length}"
puts "replaced=#{replaced}"
word =
text = "red blue red"
pattern = Regexp.new(word)
matches = text.scan(pattern)
replaced = text.gsub(pattern, "item")
puts "word=#{word}"
puts "matches=#{matches.length}"
puts "replaced=#{replaced}"
scan
`scan` returns all non-overlapping matches from a string.