-
-
Save foucist/ed99b10d44fff841beb9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
QUESTION 6: Write a function multi_gsub that performs multiple, simultaneous | |
search-and-replace operations on a string. | |
Example: | |
"Lorem Ipsum #9191".multi_gsub([[/[a-z]/i, '#'], [/#/, 'P']]) | |
=> "##### ##### P9191" | |
Answer: | |
class String | |
def multi_gsub(args) | |
pairs = args.map {|x| self.scan(x.first).map {|m| [m, x.last] }} # generate list of substitution pairs | |
re = Regexp.union(args.map {|x| x.first}) | |
self.gsub(re, Hash[*pairs.flatten]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment