views:

66

answers:

4

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?

Thanks and Regards.

A: 

$ 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

irb(main):004:0>

el_quick
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
A: 

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']
AboutRuby
A: 

how about:

@object.location =~ /[&?]v=([^&]*)/
cam
The result would be in `$1` (or you could use `url.match` as suggested by AboutRuby. This regex should work on any reasonable url though)
cam
+2  A: 
require 'net/http'
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.

mikej