Ruby Rails:如果在数组中,则从字符串中删除子字符串

Ruby Rails:如果在数组中,则从字符串中删除子字符串,ruby,arrays,string,Ruby,Arrays,String,我知道我很容易做到 现在,如果子字符串在数组中,我需要从字符串中删除每个子字符串 arr = ["1. foo", "2. bar"] string = "Only delete the 1. foo and the 2. bar" # some awesome function string = string.replace_if_in?(arr, '') # desired output => "Only delete the and the" 用于删除和调整字符串的所有函数,例如

我知道我很容易做到

现在,如果子字符串在数组中,我需要从字符串中删除每个子字符串

arr = ["1. foo", "2. bar"]
string = "Only delete the 1. foo and the 2. bar"

# some awesome function
string = string.replace_if_in?(arr, '')
# desired output => "Only delete the and the"
用于删除和调整字符串的所有函数,例如
sub
gsub
tr
。。。只接受一个单词作为参数,而不是数组。但是我的数组有20多个元素,所以我需要一种比使用
sub
20次更好的方法

不幸的是,这不仅仅是关于删除单词,而是关于删除整个子字符串作为
1。foo

如何尝试此操作?

在数组元素上使用#gsub和#join 您可以通过调用数组元素上的#join来使用#gsub,并使用regex替换运算符将它们连接起来。例如:

arr = ["foo", "bar"]
string = "Only delete the foo and the bar"
string.gsub /#{arr.join ?|}/, ''
#=> "Only delete the  and the "
string.gsub /#{arr.join ?|}/, '<bleep>'
#=> "Only delete the <bleep> and the <bleep>"
然后你可以用任何你认为合适的方式来处理剩余的空间。当你想审查单词时,这是一个更好的方法。例如:

arr = ["foo", "bar"]
string = "Only delete the foo and the bar"
string.gsub /#{arr.join ?|}/, ''
#=> "Only delete the  and the "
string.gsub /#{arr.join ?|}/, '<bleep>'
#=> "Only delete the <bleep> and the <bleep>"
string.gsub/#{arr.join?|}/,''
#=>“仅删除和”

另一方面,如果您需要考虑空白,那么split/reject/join可能是一个更好的方法链。做事总是有多种方法,你的里程数可能会有所不同。

你可以使用接受正则表达式的
gsub
,并将其与:

具体如下:

 arr = ["1. foo", "2. bar"]
 string = "Only delete the 1. foo and the 2. bar"

 arr.each {|x| string.slice!(x) }
 string # => "Only delete the  and the " 
一个扩展的功能是,这还允许您使用
regexp
服务字符裁剪文本,如
\
,或
(Uri的答案也允许):


使用
join
不是最佳选择,因为它不会转义每个元素
1中的文本。foo
也将匹配
11 foo
…仅供参考:
1。foo将匹配
11。foo
在所有答案中,所以这个答案并不比骰子决定接受你的答案差;)谢谢你们的帮助!请注意,如果
string=“仅删除1.foo和2.bar以及另一个2.bar?”
,我们会得到=>
“仅删除1.foo和2.bar以及另一个2.bar?”
这就是我们想要的吗?我不知道。冠军,你可以澄清一下。