Over a million developers have joined DZone.

Parsing A Query String With String#scan Into A Hash

·
For more information on the desired hash output, etc. see:

http://redhanded.hobix.com/inspect/injectingAHashBackwardsAndTheMergeBlock.html



qs = "post[id]=4&post[nick]=_why&post[message]=GROSS & FOO!&a=1"  # query string

hash1 = {}
hash2 = {}
resulthash = {}
count = 0

qs.scan(/(post|a)(\[|=)(.*?)(?=(&post\[|&a=|$))/) {

var = $1 << $2 << $3  


case var

when /^(post)\[(.*?)\]=(.*?)$/ then 
               count += 1
               postnum = $1 << count.to_s
               hash1.update(postnum => {$2 => $3})

when /^(a)=(.*?)$/ then resulthash.update($1 => $2)

end


}

hash1.each_pair {|k, v| hash2.update(v)}
resulthash.update("post" => hash2)

puts resulthash.inspect 

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}