Exact opposite to Ruby's CGI.parse method? Exact opposite to Ruby's CGI.parse method? ruby ruby

Exact opposite to Ruby's CGI.parse method?


There is a nice method in URI module:

require 'uri'URI.encode_www_form("q" => "ruby", "lang" => "en")  #=> "q=ruby&lang=en"


If you're using Rails (or don't mind pulling in ActiveSupport), then you can use to_param (AKA to_query):

{ :a => '&', :b => 'Where is pancake house?', :c => ['an', 'array'] }.to_param# a=%26&b=Where+is+pancake+house%3F&c%5B%5D=an&c%5B%5D=array

to_param handles arrays a little differently than your version though, it'll put out c[]=an&c[]=array rather than just c=an&c=array.


While there's no better answer, I'll put up the method which I'm using now.

def build_query(params)  params.map do |name,values|    values.map do |value|      "#{CGI.escape name}=#{CGI.escape value}"    end  end.flatten.join("&")end