How to Extract Url Parameters from a Url With Ruby or Rails

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

require 'cgi'



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

Extract url params in ruby

As I said above, you only need to escape slashes in a Regexp literal, e.g. /foo\/bar/. When defining a Regexp from a string it's not necessary:"foo/bar") produces the same Regexp as /foo\/bar/.

As to your larger problem, here's how I'd solve it, which I'm guessing is pretty much how you'd been planning to solve it:


def pattern_to_regexp(pattern)
expr = Regexp.escape(pattern) # just in case

pattern = "/foo/:foo_id/bar/:bar_id"
expr = pattern_to_regexp(pattern)
# => /\/foo\/(?<foo_id>.+?)\/bar\/(?<bar_id>.+?)/

str = "/foo/1/bar/2"
# => #<MatchData "/foo/1/bar/2" foo_id:"1" bar_id:"2">

Rails Routes: Programmatically extract params from a URL

You can parse the URL, read the query string and convert them to hash.

u = URI.parse("http://localhost:3000/blogs/213?published=true")
cgi_params = u.query.split('&').map { |e| e.split('=') }.to_h

Merge them with params that you got using Rails.application.routes.recognize_path

How to get a specific value from url in ruby on rails

Do can get it like this:

require 'uri'

url = ""

uri = URI.parse(url)
params = CGI::parse(uri.query)

params['token'] # => 'EC-xxx'

How to extract a parameter from a URL using a regex pattern

Don't use regular expressions, use a well-tested wheel.

Ruby's URI class is your friend, in particular decode_www_form:

require 'uri'

uri = URI.parse('')
uri.query # => "code=768140119"
URI.decode_www_form(uri.query) # => [["code", "768140119"]]
URI.decode_www_form(uri.query).to_h # => {"code"=>"768140119"}

As for extracting the value of a parameter of a tag, Nokogiri makes it easy, just treat the Node like a hash:

require 'nokogiri'

doc = Nokogiri::HTML("
<a href='path/to/foo'>bar</a>
")'a')['href'] # => "path/to/foo"

You don't need to waste time typing attr(...).

Related Topics

Leave a reply