DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
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





