Skip to content

Instantly share code, notes, and snippets.

@rafbm
Created September 16, 2011 16:42
Show Gist options
  • Save rafbm/1222512 to your computer and use it in GitHub Desktop.
Save rafbm/1222512 to your computer and use it in GitHub Desktop.
String#gsub version that takes two arrays: one as searches and one as replacements
class String
def gsub_array! find, replace
find.each_index do |i|
self.gsub! find[i], replace[i]
end
self
end
def gsub_array find, replace
str = self.clone
str.gsub_array! find, replace
end
end
find = ['foo', 'bar', 'baz']
replace = ['foo-2', 'bar-2', 'baz-2']
str1 = 'foo bar baz'
str2 = 'foo bar baz'
puts str1.gsub_array find, replace # foo-2 bar-2 baz-2
puts str2.gsub_array! find, replace # foo-2 bar-2 baz-2
puts str1 # foo bar baz
puts str2 # foo-2 bar-2 baz-2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment