9

I have this URL in my database, in the "location" field:

http://www.youtube.com/watch?v=xxxxxxxxxxxxxxxxxxx

I can get it with @object.location, but how can I get the value of v? I mean, get "xxxxxxxxxxxx" from the URL string?

3 Answers 3

21
require 'uri'
require 'cgi'

# use URI.parse to parse the URL into its constituent parts - host, port, query string..
uri = URI.parse(@object.location)
# then use CGI.parse to parse the query string into a hash of names and values
uri_params = CGI.parse(uri.query)

uri_params['v'] # => ["xxxxxxxxxxxxxxxxxxx"]

Note that the return from CGI.parse is a Hash of Strings to Arrays so that it can handle multiple values for the same parameter name. For your example you would want uri_params['v'][0].

Also note that the Hash returned by CGI.parse will return [] if the requested key is not found, therefore uri_params['v'][0] will return either the value or nil if the URL did not contain a v parameter.

1
  • 2
    You don't need to load net/http to get access to URI parsing. Just require 'uri' instead. Jul 18, 2012 at 21:59
0

Beyond using a library to parse the entire URL into protocol, hostname, path and parameters, you could use a simple regexp to extract the information. Note that the regexp is a quick and dirty solution, and it'll fail if there's anything at all different about the URL, like if it has another parameter after the v parameter.

url = 'http://www.youtube.com/watch?v=xxxxxxxxxxxxxxxxxxx'
video_id = url.match(/\?v=(.+)$/)[1]

You can go further with what you did by using URI::parse to get the query information.

url = 'http://www.youtube.com/watch?v=xxxxxxxxxxxxxxxxxxx'
video_id = CGI::parse(URI::parse(url).query)['v']
0
$ irb

irb(main):001:0> require 'cgi' => true
irb(main):002:0> test = CGI::parse('v=xxxxxxxxxxxxxxxxxxx') => {"v"=>["xxxxxxxxxxxxxxxxxxx"]}
irb(main):003:0> puts test['v']
xxxxxxxxxxxxxxxxxxx
=> nil
1
  • That's what I was trying to think of. I was looking in URI::HTTP and couldn't find any methods to parse the parameters.
    – AboutRuby
    Aug 23, 2010 at 22:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.