CGI.parse takes a querystring and returns a hash. I'm looking for a way to do the inverse. Any suggestions?
| SitePoint Sponsor |
CGI.parse takes a querystring and returns a hash. I'm looking for a way to do the inverse. Any suggestions?


given "hash" as a hash, try hash.to_query and see if that's what you're looking for.
Close, but not quite. CGI.parse gives back an array of values, even when there is just one. to_query interprets this as the value being present multiple times. I just wrote my own implementation, but if a standard solution existed, I would have preferred to use that.
Code:my_hash.map { |key, value| "#{key}=#{CGI.escape(value)}" }.join('&')
Ohai!
Not quite. The result from CGI.parse looks like this:
Which does make sense, but also means that the serialization code becomes a bit more tricky. Anyway, I figured it out - it's just that if some kind of standard function existed, I would rather have used that.Code:irb(main):002:0> CGI.parse "foo=42&bar[]=1&bar[]=2&bar[]=3" => {"bar[]"=>["1", "2", "3"], "foo"=>["42"]}
Just in case somebody else needs this, here's the code I came up with:
Code:require 'uri' def hash_to_query(h) h.map do |k, v| v.map do |value| (value.nil?) ? URI.encode(k.to_s) : "%s=%s" % [URI.encode(k.to_s), URI.encode(value.to_s)] end end.flatten.join("&") end
Bookmarks