Take the 2-minute tour ×

I have a string like this:


Does Ruby on Rails provide methods to parse this as if it is a querystring, so I get a hash like this:

    :foo => "bar",
    :bar => "foo",
    :hello => "hi"

Or must I write it myself?


Please note that the string above is not a real querystring from a URL, but rather a string stored in a cookie from Facebook Connect.

share|improve this question
add comment

4 Answers

up vote 39 down vote accepted

The answer depends on the version of Rails that you are using. If you are using 2.3 or later, use Rack's builtin parser for params

 Rack::Utils.parse_nested_query("a=2") #=> {"a" => "2"}

If you are on older Rails, you can indeed use CGI::parse. Note that handling of hashes and arrays differs in subtle ways between modules so you need to verify whether the data you are getting is correct for the method you choose.

You can also include Rack::Utils into your class for shorthand access.

share|improve this answer
no need to include: Rack::Utils.parse_nested_query("a=2") –  tokland May 23 '12 at 8:36
add comment

Edit : as said in the comments, symolizing keys can bring your server down if someone want to hurt you. I still do it a lot when I work on low profile apps because it makes things easier to work with but I wouldn't do it anymore for high stake apps

Do not forget to symbolize the keys for obtaining the result you want


this operation is destructive for duplicates.

share|improve this answer
Symbolizing user-supplied keys is a bad idea. Symbols do not GC, so if someone spams your server with alot of bogus parameter keys it will exhaust the process memory at some point. –  Julik Jun 30 '12 at 22:49
add comment



Gives you

share|improve this answer
This is the only implementation I've tried that handles multiple instances of each param -- Thanks! –  Ryan Long Jun 26 '12 at 20:58
Problem is that most people don't want arrays and are expecting a simple key=>value response –  babonk Sep 5 '13 at 23:45
add comment

The params hash should have what you want.


share|improve this answer
add comment

Your Answer

