In my app I need to be able to find all number substrings, then scan each one, find the first one that matches a range (such as between 5 and 15) and replace THAT instance with another string “X”.
My test string s = "1 foo 100 bar 10 gee 1"
My initial pattern is any string of 1 or more digits, eg, re = Regexp.new(/\d+/)
matches = s.scan(re) gives ["1", "100", "10", "1"]
If I want to replace the Nth match, and only the Nth match, with “X” how do I?
For example if I want to replace the third match “10” (matches[2]) I can’t just say
s[matches[2]] = "X" because that does two replacements
"1 foo X0 bar X gee 1"
Any help would be appreciated!
String#gsubhas a form that takes a block. It yields to the block for each match, and replaces the match with the result of the block. So: