获取URL字符串参数?

el_*_*ick 9 ruby url ruby-on-rails

我在我的数据库中的"位置"字段中有此URL:

http://www.youtube.com/watch?v=xxxxxxxxxxxxxxxxxxx
Run Code Online (Sandbox Code Playgroud)

我可以得到它@object.location,但我怎样才能得到它的价值v?我的意思是,"xxxxxxxxxxxx"从URL字符串中获取?

mik*_*kej 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"]
Run Code Online (Sandbox Code Playgroud)

请注意,从返回CGI.parseHashStrings,以Arrays使其可以处理多个值相同的参数名称.对于你想要的例子uri_params['v'][0].

另请注意,如果找不到请求的密钥,则Hash返回的CGI.parse将返回[],因此uri_params['v'][0]将返回值或nilURL不包含v参数.

  • 您不需要加载`net/http`来访问URI解析.只需要'需要'uri'. (2认同)