I need to remove some phrases from a string in Ruby. The phrases are defined inside an array. It could look like this:
我需要从Ruby中的字符串中删除一些短语。短语在数组中定义。它可能是这样的:
remove = ["Test", "Another One", "Something Else"]
Then I want to check and remove these from a given string.
然后我要检查并从给定的字符串中删除它们。
"This is a Test" => "This is a " "This is Another One" => "This is " "This is Another Two" => "This is Another Two"
"这是一个测试" => "这是"这是另一个" => "这是"这是另外两个" => "这是另外两个"
Using Ruby 1.9.3 and Rail 3.2.6.
使用Ruby 1.9.3和rails 3.2.6。
2 个解决方案
#1
5
ary = ["Test", "Another One", "Something Else", "(RegExp i\s escaped)"]
string.gsub(Regexp.union(ary), '')
Regexp.union
can be used to compile an array of strings (or regexpes) into a single regexp which therefore only requires a single search & replace.
Regexp。可以使用union将字符串数组(或regexpes)编译为一个regexp,因此只需要一个搜索和替换。
Regexp.union ['string', /regexp?/i] #=> /string|(?i-mx:regexp?)/
#2
1
Simplest (but not most efficient):
最简单的(但不是最有效的):
# Non-mutating
cleaned = str
remove.each{ |s| cleaned = cleaned.gsub(s,'') }
# Mutating
remove.each{ |s| str.gsub!(s,'') }
More efficient (but less clear):
更有效率(但不太清楚):
# Non-mutating
cleaned = str.gsub(Regexp.union(remove), '')
# Mutating
str.gsub!(Regexp.union(remove), '')
#1
5
ary = ["Test", "Another One", "Something Else", "(RegExp i\s escaped)"]
string.gsub(Regexp.union(ary), '')
Regexp.union
can be used to compile an array of strings (or regexpes) into a single regexp which therefore only requires a single search & replace.
Regexp。可以使用union将字符串数组(或regexpes)编译为一个regexp,因此只需要一个搜索和替换。
Regexp.union ['string', /regexp?/i] #=> /string|(?i-mx:regexp?)/
#2
1
Simplest (but not most efficient):
最简单的(但不是最有效的):
# Non-mutating
cleaned = str
remove.each{ |s| cleaned = cleaned.gsub(s,'') }
# Mutating
remove.each{ |s| str.gsub!(s,'') }
More efficient (but less clear):
更有效率(但不太清楚):
# Non-mutating
cleaned = str.gsub(Regexp.union(remove), '')
# Mutating
str.gsub!(Regexp.union(remove), '')