2

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.

1
  • 1
    If you're using a web framework, then you're asking the wrong question because the framework likely does this for you. Commented Jul 16, 2017 at 23:46

4 Answers 4

3

If you strip off the ? part and trim after #, then you get this:

require 'cgi'

CGI.parse("q=cat&name=Tim")
# => {"q"=>["cat"], "name"=>["Tim"]}

So pre-process with:

query = query.sub(/\A\?/, '').sub(/\#.*/, '')
Sign up to request clarification or add additional context in comments.

Comments

2

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"]}

Comments

0

You should use a library but here's a regex solution anyway:

str = "?q=cat&name=Tim#img=FunnyCat"

r1 = /(?<=\?).+?(?=#)/
r2 = /&|=/

str[r1].split(r2).each_slice(2).to_h 
 #=> {"q"=>"cat", "name"=>"Tim"}

Comments

0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.