Skip to content

Instantly share code, notes, and snippets.

@andrewheins
Created December 7, 2011 17:29
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save andrewheins/1443695 to your computer and use it in GitHub Desktop.
Save andrewheins/1443695 to your computer and use it in GitHub Desktop.
QueryString to Hash in Ruby
# Today's little useless tidbit converts a url's query string into a hash
# set of k/v pairs in a way that merges duplicates and massages empty
# querystring values
def qs_to_hash(querystring)
keyvals = query.split('&').inject({}) do |result, q|
k,v = q.split('=')
if !v.nil?
result.merge({k => v})
elsif !result.key?(k)
result.merge({k => true})
else
result
end
end
keyvals
end
qs_to_hash("a=b&b=c&c=d") # {a=>b, b=>c, c=>d}
qs_to_hash("a=b&b=c&c") # {a=>b, b=>c, c=>true} nil becomes true
qs_to_hash("a=b&b=c&a=d") # {a=>d, b=>c} last declaration wins
qs_to_hash("a=b&b=c&a") # {a=>b, b=>c} nils don't override set vals
# Now, of course Rails's implementation is much smarter than this...
# but you never know.
@fmontes86
Copy link

In line 6, in the passing parameter, i think you mean "querystring" intead of "query".

Cheers!

@iprog21
Copy link

iprog21 commented Apr 9, 2020

typo bro. line 6. :)

this works also.

CGI.parse(URI.parse(url).query)

@c80609a
Copy link

c80609a commented Nov 29, 2021

CGI.parse(URI.parse(url).query) is not the same:

url = 'https://google.com?q=success'

CGI.parse(URI.parse(url).query)
#=> {"q"=>["success"]}

CGI.unescape CGI.parse(URI.parse(url).query).to_query
#=> "q[]=success"

@YaEvan
Copy link

YaEvan commented Nov 30, 2021

use rails activesupport's to_query and rack parse_nested_query
query_string = CGI.unescape(hash.to_query) hash = Rack.parse_nested_query(query_string)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment