Hey I need to figure out how to turn this string
"?q=cat&name=Tim#img=FunnyCat"
into the hash
({"q" => "cat", "name" => "Tim"})
I'm very much stuck on this problem any assistance would be greatly appreciated.
Hey I need to figure out how to turn this string
"?q=cat&name=Tim#img=FunnyCat"
into the hash
({"q" => "cat", "name" => "Tim"})
I'm very much stuck on this problem any assistance would be greatly appreciated.
I suggest you use URI.parse and CGI.parse. URI.parse will help you get the query easily, while CGI.parse will do the actual job of parsing the query and transforming it into a hash.
require 'uri'
require 'cgi'
CGI.parse(URI.parse('?q=cat&name=Tim#img=FunnyCat').query)
this will return {"q"=>["cat"], "name"=>["Tim"]}
r = /
[[:alpha:]]+ # match 1 or more letters
= # match '='
[[:alpha:]]+
(?=&) # match '&' in positive lookahead
| # or
(?<=&) # match '&' in positive lookbehind
[[:alpha:]]+
=
[[:alpha:]]+
/x # free-spacing regex definition mode
str = "?q=cat&name=Tim#img=FunnyCat"
str.gsub(r).each_with_object({}) do |s,h|
k, v = s.split('=')
h[k] = v
end
#=> {"q"=>"cat", "name"=>"Tim"}
This uses the form of String#gsub that has no block and therefore returns an enumerator. Note that no character substitutions are performed. I've found several situations where it has been helpful to use gsub in this way.