Skip to content

Instantly share code, notes, and snippets.

@foucist

foucist/quiz.rb Secret

Created March 4, 2015 17:27
Show Gist options
  • Save foucist/ed99b10d44fff841beb9 to your computer and use it in GitHub Desktop.
Save foucist/ed99b10d44fff841beb9 to your computer and use it in GitHub Desktop.
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