gpt4 book ai didi

ruby - 导轨 : Remove substring from the string if in array

转载 作者:数据小太阳 更新时间:2023-10-29 08:16:20 25 4
gpt4 key购买 nike

我知道我可以很容易地remove a substring from a 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"

所有去除调整字符串的函数,比如sub, gsub, tr, ...只取一个单词作为参数,而不是数组。但是我的数组有超过 20 个元素,所以我需要一种比使用 sub 20 次更好的方法。

遗憾的是,它不仅是关于删除单词,而是关于删除整个子字符串作为 1。富

我该如何尝试?

最佳答案

您可以使用接受正则表达式的 gsub,并将其与 Regexp.union 结合使用:

string.gsub(Regexp.union(arr), '')
# => "Only delete the and the "

关于ruby - 导轨 : Remove substring from the string if in array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27194494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com