Ruby: Find all occurrences of a pattern in a string, manipulate, and then replace

regex, ruby

Solution

You can use `gsub` with a block, so

string.gsub(/\s[aeiou]\w{1,}/i) do |word|
  word.upcase
end

Problem

I'm looking for a way to search for all occurrences of a pattern in a string, perform some nontrivial manipulation of the string returned, and then replace it. Ruby's String#gsub! method isn't a good fit because I need to take the returned occurrence and then manipulate it to come up with the value that will be used to replace it. Ruby's String#scan method, of course, can be used to find all occurrences of the pattern but I'm not sure how to replace the returned occurrences once I've made the necessary changes to them. The code example below is not what I'm actually working on demonstrates the sort of thing I'm attempting to accomplish. ``` # String string = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." # Look for all words that start with a vowel string.scan(/\s[aeiou]\w{1,}/i).each do |word| # Manipulate the words that match the pattern word.upcase # Replace the word in the string with the manipulated value # Need some help here end # Print the modified string puts string ```

Original source