views:

223

answers:

4

I have a string like this:

"foo=bar&bar=foo&hello=hi"

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?

EDIT

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.

A: 

The params hash should have what you want.

http://rails.nuvvo.com/lesson/6371-action-controller-parameters

Paul
Nono, what I mean, I don't want to parse the querystring, I want to make a string in a variable act as a querystring.
Time Machine
A: 

I don't think there is something like this in ruby methods. You have to write method for yourself similar to following.

strs= "foo=bar&bar=foo&hello=hi"
@quesy_hash={}
for str in strs.split("&")
   s= str.split("=")
   @quesy_hash[s[0]]= s[1]
end

Hope that Helps.

No check though.

Salil
A: 

The

CGI::parse("foo=bar&bar=foo&hello=hi")

Gives you

{"foo"=>["bar"], "hello"=>["hi"], "bar"=>["foo"]}
dombesz
A: 

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

 include 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.

Julik