Skip to content

Instantly share code, notes, and snippets.

@epitron
Forked from foucist/quiz.rb
Last active August 29, 2015 14:16
Show Gist options
  • Save epitron/3a669e0ae6e83e11836c to your computer and use it in GitHub Desktop.
Save epitron/3a669e0ae6e83e11836c to your computer and use it in GitHub Desktop.
Multi-replace problem
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"
class String
def mgsub(opts)
u = Regexp.union(opts.keys)
gsub(u) do |m|
opts.find { |re, s| m =~ re }.last
end
end
end
p "Lorem Ipsum #9191".mgsub(/[a-z]/i => '#', /#/ => 'P')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment