Get URL and parse query string using Ruby

As I’ve been learning Ruby, I’ve needed to do some of the simplest things, such as getting the current URL and parsing out the query string, things that are basic in the other languages i know. I was struggling to find out how to parse query string using ruby.

Such as getting the current URL and parsing out the query string into key/value pairs.

Searching Google for “parse URL using Ruby”, “Get URL with Ruby”, “Get URI with Ruby”, “Ruby get URL” (and many other variants) – all return loads of results – all of them utter crap.

They present examples of how to parse the URL using a predefined string that represents a URI, such as http://www.wasteoftime.com?use=none&to=anyone&why=youTellMe which is completely useless and does not show you how to GET the URL!!!

So for any fellow beginners of Ruby that may have been round the houses, here you go:

puts ENV['REQUEST_URI']

Seriously. I was ashamed of myself that i didn’t even guess that (after all, i access the same thing in PHP using $_SERVER[‘REQUEST_URI’]). After learning that, first thing i did was a ENV.inspect, inspect being the equivalent-ish of var_dump(), or print_r().

So, to _actually_ get the query string, i did: (i have added comments to help try to help fellow learners of Ruby)

# define an array first
qs = {}
# split QUERY_STRING on & and each through them
ENV['QUERY_STRING'].split(/[&]/).each do | kv |
# now split on the = and set k and v (short for key, value)
k, v = kv.split(/[=]/)
# fill the qs array
qs[k] = v
end

So if we had a URL like so: http://www.tizardsbriefcase.com?domain=stuarts&tld=.me.uk&p=2&r=abc we would end up with an array looking like this:

qs[domain] = 'stuarts'
qs[tld] = 'me.uk'
qs[p] = 2
qs[r] = 'abc'

Ace, now i have an array called qs containing all my passed in data. Stupidly easy when you know how, but that’s the joys of learning a new language eh :)




2 Comments

Thanks a lot. I’m just beginning, and had the same experience, including the noise of Rails. You should know though that this article came up as result #9 in my Google search for “ruby get url” and was my 2nd read (skipped the ones with “Rail(s)” in the title.

Again; thanks.

Hi Thomas,

Glad you found it helpful, i had a small nightmare trying to find helpful stuff that wasn’t Rails oriented. Hence the mild annoyance thats obvious in my post i guess.

Thanks for your kind words and feedback.

Stuart.

Leave a Reply

Your email address will not be published. Required fields are marked *