Shpigford
Shpigford

Reputation: 25348

Split string into a hash?

I have the following example string:

"[email protected]&user_id=13&last_seen=January 14, 2013"

And I need is converted to a hash:

{ :email=>[email protected], :user_id=>13, :last_seen => 'January 14, 2013' }

How can I do that? The keys and values could be anything (they won't always be email and user_id) and there could be dozens of them.

Upvotes: 2

Views: 223

Answers (3)

Arup Rakshit
Arup Rakshit

Reputation: 118271

How about the below :

require 'uri'

str = "[email protected]&user_id=13&last_seen=January 14, 2013"
URI.decode_www_form(str)
# => [["email", "[email protected]"],
#     ["user_id", "13"],
#     ["last_seen", "January 14, 2013"]]
Hash[URI.decode_www_form(str)]
# => {"email"=>"[email protected]",
#     "user_id"=>"13",
#     "last_seen"=>"January 14, 2013"}

Upvotes: 0

Mori
Mori

Reputation: 27789

str = "[email protected]&user_id=13&last_seen=January 14, 2013"
Hash[*str.split(/=|&/)]

If you're in Rails you can symbolize keys with Hash#symbolize_keys, else you can do it yourself.

Upvotes: 3

Chris Mowforth
Chris Mowforth

Reputation: 6723

Use the CGI library you already get for free:

require 'cgi'

parsed = CGI.parse("[email protected]&user_id=13&last_seen=January 14, 2013")

# => {"email"=>["[email protected]"], "user_id"=>["13"], "last_seen"=>["January 14, 2013"]}

Or if you're using rack:

require 'rack/utils'

parsed = Rack::Utils.parse_query("[email protected]&user_id=13&last_seen=January 14, 2013")

# => {"email"=>"[email protected]", "user_id"=>"13", "last_seen"=>"January 14, 2013"}

Upvotes: 7

Related Questions