Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string into a hash?

Tags:

string

ruby

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.

like image 279
Shpigford Avatar asked Jul 29 '26 22:07

Shpigford


1 Answers

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"}
like image 167
Chris Mowforth Avatar answered Aug 01 '26 14:08

Chris Mowforth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!