Skip to content

Instantly share code, notes, and snippets.

@millisami
Forked from andrewheins/qs_to_hash.rb
Last active September 6, 2017 19:50
Show Gist options
  • Save millisami/5966043 to your computer and use it in GitHub Desktop.
Save millisami/5966043 to your computer and use it in GitHub Desktop.
# 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(query_string)
keyvals = query_string.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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment