我知道我可以轻松地从字符串中删除子字符串。
现在,如果子字符串在数组中,则需要从字符串中删除每个子字符串。
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
我将如何尝试呢?
如下所示:
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的答案也允许):
string = "Only delete the 1. foo and the 2. bar and \\...."
arr = ["1. foo", "2. bar", "\..."]
arr.each {|x| string.slice!(x) }
string # => "Only delete the and the and ."
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句