如何移除数组中含另一数组子串的字符串?Ruby技术问题
移除数组中包含指定子串的元素
原始数据
string_array = ["firstname@domain.com.au", "lastname@domaintwo.com.au"] domains = ["@domain.com.au", "firstname"]
需求
移除string_array中包含domains数组内任意子串的元素。
错误原因分析
- 最初写的
domains.include?(item)是判断整个元素是否存在于domains数组中,和需求不符,因此结果没有变化。 - 后来尝试的
item.include?(domains)报错是因为字符串的include?方法仅接受字符串参数,传入数组会触发类型转换错误。
正确实现方法
方法一:使用any?遍历子串检查
test = string_array.reject { |item| domains.any? { |substr| item.include?(substr) } } # => ["lastname@domaintwo.com.au"]
逻辑说明:
domains.any? { ... }会逐个检查domains里的子串,只要当前item包含其中任意一个子串,就返回true。reject方法会移除所有返回true的元素,最终留下不包含任何指定子串的元素。
方法二:使用正则表达式批量匹配
如果domains里的子串数量较多,用正则表达式的方式更高效:
domain_regex = Regexp.union(domains) test = string_array.reject { |item| item.match?(domain_regex) } # => ["lastname@domaintwo.com.au"]
逻辑说明:
Regexp.union(domains)会把数组中的所有子串合并成一个正则表达式,可匹配任意一个子串。item.match?(domain_regex)判断元素是否匹配该正则,匹配则被reject移除。
内容的提问来源于stack exchange,提问作者TotalApproved
相关产品推荐
相关产品推荐

