Created
September 16, 2011 16:42
-
-
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
This file contains hidden or 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
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