Ruby: How to turn a hash into HTTP parameters?

Julien Genestoux picture Julien Genestoux · Apr 28, 2009 · Viewed 133.5k times · Source

That is pretty easy with a plain hash like

{:a => "a", :b => "b"} 

which would translate into

"a=a&b=b"

But what do you do with something more complex like

{:a => "a", :b => ["c", "d", "e"]} 

which should translate into

"a=a&b[0]=c&b[1]=d&b[2]=e" 

Or even worse, (what to do) with something like:

{:a => "a", :b => [{:c => "c", :d => "d"}, {:e => "e", :f => "f"}]

Thanks for the much appreciated help with that!

Answer

Gabe Martin-Dempesy picture Gabe Martin-Dempesy · Sep 30, 2010

For basic, non-nested hashes, Rails/ActiveSupport has Object#to_query.

>> {:a => "a", :b => ["c", "d", "e"]}.to_query
=> "a=a&b%5B%5D=c&b%5B%5D=d&b%5B%5D=e"
>> CGI.unescape({:a => "a", :b => ["c", "d", "e"]}.to_query)
=> "a=a&b[]=c&b[]=d&b[]=e"

http://api.rubyonrails.org/classes/Object.html#method-i-to_query