I have the following function that decodes a URL into a hash comprised of different pieces of the URL. For example, after the first line where I assign hash, I receive this output:
>> CGI.parse(URI.parse("http://google.com/?foo=bar&baz=hello").query)
=> {"foo"=>["bar"], "baz"=>["hello"]}
In this function, I’m trying to pull values if the key is “p” or “q”. I essentially want to filter the hash into only the keys and values I want.
My goal is to only show the keywords someone searches for such as brick or cement.
Here’s my function:
def self.get_search_terms(search_url)
hash = CGI.parse(URI.parse(URI.encode(search_url)).query) #returns a hash
keywords = []
hash.each do |key|
if key["q"] != nil ||
key["p"] != nil
keywords << key
end
end
keywords
end
One way to do it: