Never been to DZone Snippets before?

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

About this user

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

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 

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS