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

Ruby on-RailsRubyUriUrl Parameters

Ruby on-Rails Problem Overview


I have some URLs, like

http://www.example.com/something?param1=value1&param2=value2&param3=value3

and I would like to extract the parameters from these URLs and get them in a Hash. Obviously, I could use regular expressions, but I was just wondering if there was easier ways to do that with Ruby or Rails. I haven't found anything in the Ruby module URI but perhaps I missed something.

In fact, I need a method that would do that:

extract_parameters_from_url("http://www.example.com/something?param1=value1&param2=value2&param3=value3")
#=> {:param1 => 'value1', :param2 => 'value2', :param3 => 'value3'}

Would you have some advices?

Ruby on-Rails Solutions


Solution 1 - Ruby on-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"]}

Solution 2 - Ruby on-Rails

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"}

Solution 3 - Ruby on-Rails

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" } 

Solution 4 - Ruby on-Rails

For a pure Ruby solution combine URI.parse with CGI.parse (this can be used even if Rails/Rack etc. are not required):

CGI.parse(URI.parse(url).query) 
# =>  {"name1" => ["value1"], "name2" => ["value1", "value2", ...] }

Solution 5 - Ruby on-Rails

There more than one ways, to solve your problem. Others has shown you the some tricks. I know another trick. Here is my try :-

require 'uri'
url = "http://www.example.com/something?param1=value1&param2=value2&param3=value3"
uri = URI(url)
# => #<URI::HTTP:0x89e4898 URL:http://www.example.com/something?param1=value1&param2=value2&param3=value3>
URI::decode_www_form(uri.query).to_h # if you are in 2.1 or later version of Ruby
# => {"param1"=>"value1", "param2"=>"value2", "param3"=>"value3"}
Hash[URI::decode_www_form(uri.query)] # if you are below 2.1 version of Ruby
# => {"param1"=>"value1", "param2"=>"value2", "param3"=>"value3"}

Read the method docomentation of ::decode_www_form.

Solution 6 - Ruby on-Rails

Check out the addressable gem - a popular replacement for Ruby's URI module that makes query parsing easy:

require "addressable/uri"
uri = Addressable::URI.parse("http://www.example.com/something?param1=value1&param2=value2&param3=value3")
uri.query_values['param1']
=> 'value1'

(It also apparently handles param encoding/decoding, unlike URI)

Solution 7 - Ruby on-Rails

Using CGI might be an outdated approach with Ruby 2.7/3.

Here's a neat way to do this with URI:

uri = URI.parse 'https://duckduckgo.com/?q=ruby+programming+language'
params = Hash[URI.decode_www_form uri.query]
# => {"q"=>"ruby programming language"} 

Solution 8 - Ruby on-Rails

you can also use this method


require 'uri'
require 'cgi'
uri = URI("https://example.com/?query=1&q=2&query=5")
a = CGI::parse(uri.query)
puts a                   #=> {"query"=>["1", "5"], "q"=>["2"]}
puts a["query"].to_s     #=> ["1", "5"]
puts a["query"][0]       #=>  1
puts a["query"][1]       #=>  5
puts a["q"][0]           #=>  2


its safe and much easier

Solution 9 - Ruby on-Rails

Sadly both the URI and addressable libraries break when attempting to extract query params from buggy URLs. E.g. this breaks both:

http://localhost:4300/webapp/foo/#//controller/action?account=001-001-111&email=john%40email.com

Building on Arthur / Levi's solution, with url.split("?").try(:last) you can grab just the query param portion of the URL, and use Rack::Utils.parse_nested_query to parse that string of parameters into a hash.

Or in full:

Rack::Utils.parse_nested_query(url.split("?").try(:last))

returning in my example:

{"account": "001-001-111", "email": "[email protected]"}

Solution 10 - Ruby on-Rails

In your Controller, you should be able to access a dictionary (hash) called params. So, if you know what the names of each query parameter is, then just do params[:param1] to access it... If you don't know what the names of the parameters are, you could traverse the dictionary and get the keys.

Some simple examples here.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFlackouView Question on Stackoverflow
Solution 1 - Ruby on-RailsLuqmanView Answer on Stackoverflow
Solution 2 - Ruby on-RailsArthur GunnView Answer on Stackoverflow
Solution 3 - Ruby on-RailsrtdpView Answer on Stackoverflow
Solution 4 - Ruby on-RailsalupView Answer on Stackoverflow
Solution 5 - Ruby on-RailsArup RakshitView Answer on Stackoverflow
Solution 6 - Ruby on-RailsYarinView Answer on Stackoverflow
Solution 7 - Ruby on-RailsDmitrii KharlamovView Answer on Stackoverflow
Solution 8 - Ruby on-RailsPolarspetrollView Answer on Stackoverflow
Solution 9 - Ruby on-RailsKelsey HannanView Answer on Stackoverflow
Solution 10 - Ruby on-RailskafuchauView Answer on Stackoverflow