从ruby字符串中删除否定项(前面带减号的项)的问题



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

我假设在参数哈希中q的值将是:

"Arnold Schwarz -applesauce -cantaloop"

我希望能够在ruby中填充一个数组,从字符串中提取所有负项。下面是我的代码,似乎不能正常工作。它将-苹果酱从query_string中去除并放入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?('-')}

最新更新