How to extract URL parameters from a URL with Ruby or Rails? How to extract URL parameters from a URL with Ruby or Rails? ruby ruby

How to extract URL parameters from a URL with Ruby or Rails?


I think you want to turn any given URL string into a HASH?

You can try http://www.ruby-doc.org/stdlib/libdoc/cgi/rdoc/classes/CGI.html#M000075

require 'cgi'CGI::parse('param1=value1&param2=value2&param3=value3')

returns

{"param1"=>["value1"], "param2"=>["value2"], "param3"=>["value3"]}


I found myself needing the same thing for a recent project.Building on Levi's solution, here's a cleaner and faster method:

Rack::Utils.parse_nested_query 'param1=value1&param2=value2&param3=value3'# => {"param1"=>"value1", "param2"=>"value2", "param3"=>"value3"}


Just Improved with Levi answer above -

Rack::Utils.parse_query URI("http://example.com?par=hello&par2=bye").query

For a string like above url, it will return

{ "par" => "hello", "par2" => "bye" }