从 ruby 字符串中删除否定词(前面有减号的词)有问题吗?

Issue with removing negation terms (terms with a minus before them) from a ruby string?

我们的 rails 应用程序的最终用户可以在 url 参数中传递一个否定词。这是一个前面有减号的术语。示例如下:localhost:80/search?q=Arnold+Schwarz+-applesauce+-cantaloop

我假设在参数散列中 q 的值将是:

"Arnold Schwarz -applesauce -cantaloop"

我希望能够在 ruby 中填充一个数组,从字符串中提取所有否定词。下面是我的代码,它似乎无法正常工作。它从 query_string 中删除 -applesauce 并将其放入 ret_hash["excluded_terms"],但不会删除 -cantaloop.

query_string = "Arnold Schwarz -applesauce -cantaloop"
exclude_terms = Array.new 

def compose_valid_query_string(query_string)
    split_string = query_string.split
    ret_hash = {}
    split_string.each do |term|
        if(term.start_with?("-"))
            deleted_term = split_string.delete(term)
            ( ret_hash["excluded_terms"] ||= [] ) << deleted_term
        end
    end
    ret_hash["query_string"] = split_string
    return ret_hash
end

问题是您在遍历数组时删除了数组中的元素。在这些情况下究竟发生了什么是未定义的,但它足以导致迭代跳过元素。

执行此操作的另一种方法是使用分区,例如,它将可枚举拆分为块为真的那些元素和其余部分。

negative, positive = split_string.partition {|term| term.start_with?('-')}